Skip to content

Commit 0f939a8

Browse files
committed
feat: Implemented a new function to swaap numbers without dummy variable
1 parent ede7215 commit 0f939a8

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
def xor_swap(a: int, b: int) -> (int, int):
2+
"""
3+
Swap two integers using bitwise XOR
4+
without using a temporary variable.
5+
6+
This algorithm utilizes the properties
7+
of the bitwise XOR operation to swap the values
8+
of two integers `a` and `b` without
9+
the use of a temporary variable. XOR swap is a
10+
rarely used trick but showcases the power
11+
of bit manipulation for efficient operations
12+
at the hardware level.
13+
14+
The steps involved are:
15+
1. `a = a ^ b`
16+
2. `b = a ^ b` (Now `b` holds the original value of `a`)
17+
3. `a = a ^ b` (Now `a` holds the original value of `b`)
18+
19+
Although this technique can swap variables
20+
without extra space, it is generally not
21+
recommended in production code because it is
22+
less readable than using a temporary variable.
23+
24+
Args:
25+
a (int): The first integer to be swapped.
26+
b (int): The second integer to be swapped.
27+
28+
Returns:
29+
(int, int): The swapped values of `a` and `b`.
30+
31+
Raises:
32+
None
33+
34+
Example:
35+
>>> xor_swap(5, 10)
36+
(10, 5)
37+
>>> xor_swap(0, 100)
38+
(100, 0)
39+
>>> xor_swap(-3, 9)
40+
(9, -3)
41+
42+
Notes:
43+
- Swapping using XOR can lead to confusion and
44+
should generally be avoided in
45+
favor of more readable methods.
46+
- This algorithm does not work if both `a` and `b`
47+
refer to the same variable.
48+
49+
"""
50+
if a == b:
51+
print("Both values are the same; no swap needed.")
52+
return a, b
53+
54+
# print(f"Original a = {a}, b = {b}")
55+
a = a ^ b # Step 1
56+
b = a ^ b # Step 2: Now b is the original value of a
57+
a = a ^ b # Step 3: Now a is the original value of b
58+
# print(f"Swapped a = {a}, b = {b}")
59+
return a, b
60+
61+
62+
if __name__ == "__main__":
63+
import doctest
64+
doctest.testmod()
65+
print(xor_swap(5, 10)) # (10, 5)
66+
print(xor_swap(0, 100)) # (100, 0)
67+
print(xor_swap(-3, 9)) # (9, -3)
68+
+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# print(f"Swapped a = {a}, b = {b}")

0 commit comments

Comments
 (0)