Skip to content

Commit 2f5172d

Browse files
author
Balamurugan315
committed
Add XOR-based swap algorithm for two numbers
1 parent a71618f commit 2f5172d

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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()

0 commit comments

Comments
 (0)