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
+
0 commit comments