Skip to content

Commit a3806f7

Browse files
Balamurugan315Balamurugan315cclauss
authored
Add XOR-based swap algorithm for two numbers (#13018)
* Add XOR-based swap algorithm for two numbers * updating DIRECTORY.md * Include additional test case for xor_swap function Add example for xor_swap with larger integers --------- Co-authored-by: Balamurugan315 <balamuruganmsde@gmail.com> Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: cclauss <cclauss@users.noreply.github.com>
1 parent ff206e6 commit a3806f7

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

‎DIRECTORY.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@
106106
* [Rotate Bits](bit_manipulation/rotate_bits.py)
107107
* [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py)
108108
* [Swap All Odd And Even Bits](bit_manipulation/swap_all_odd_and_even_bits.py)
109+
* [Xor Swap Two Integers](bit_manipulation/xor_swap_two_integers.py)
109110

110111
## [Blockchain](blockchain)
111112
* [Diophantine Equation](blockchain/diophantine_equation.py)
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
>>> xor_swap(12345, 54321)
29+
(54321, 12345)
30+
"""
31+
a = a ^ b
32+
b = a ^ b
33+
a = a ^ b
34+
return a, b
35+
36+
37+
if __name__ == "__main__":
38+
import doctest
39+
40+
doctest.testmod()

0 commit comments

Comments
 (0)