File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Information on XOR swap: https://en.wikipedia.org/wiki/Bitwise_operation#XOR
2+
3+ # Algorithm:
4+ # 1. Take two integers a and b.
5+ # 2. Apply XOR between a and b and store the result in a:
6+ # a = a ^ b
7+ # 3. XOR the new value of a with b to get the original value of a and store it in b:
8+ # b = a ^ b
9+ # 4. XOR the new value of a with the new value of b.
10+ # This gives the original value of b, which we store in a:
11+ # a = a ^ b
12+ # 5. Return the swapped values (a, b).
13+ # This method swaps two numbers without using a temporary variable.
14+
15+
16+ def xor_swap (a : int , b : int ) -> tuple [int , int ]:
17+ """
18+ Swap two integers using bitwise XOR operation and return the swapped values.
19+
20+ >>> xor_swap(5, 10)
21+ (10, 5)
22+ >>> xor_swap(0, 0)
23+ (0, 0)
24+ >>> xor_swap(-1, 1)
25+ (1, -1)
26+ >>> xor_swap(123, 456)
27+ (456, 123)
28+ """
29+ a = a ^ b
30+ b = a ^ b
31+ a = a ^ b
32+ return a , b
33+
34+
35+ if __name__ == "__main__" :
36+ import doctest
37+
38+ doctest .testmod ()
You can’t perform that action at this time.
0 commit comments