Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@
* [Rotate Bits](bit_manipulation/rotate_bits.py)
* [Single Bit Manipulation Operations](bit_manipulation/single_bit_manipulation_operations.py)
* [Swap All Odd And Even Bits](bit_manipulation/swap_all_odd_and_even_bits.py)
* [Xor Swap Two Integers](bit_manipulation/xor_swap_two_integers.py)

## [Blockchain](blockchain)
* [Diophantine Equation](blockchain/diophantine_equation.py)
Expand Down
40 changes: 40 additions & 0 deletions bit_manipulation/xor_swap_two_integers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Information on XOR swap: https://en.wikipedia.org/wiki/Bitwise_operation#XOR

# Algorithm:
# 1. Take two integers a and b.
# 2. Apply XOR between a and b and store the result in a:
# a = a ^ b
# 3. XOR the new value of a with b to get the original value of a and store it in b:
# b = a ^ b
# 4. XOR the new value of a with the new value of b.
# This gives the original value of b, which we store in a:
# a = a ^ b
# 5. Return the swapped values (a, b).
# This method swaps two numbers without using a temporary variable.


def xor_swap(a: int, b: int) -> tuple[int, int]:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: a

Please provide descriptive name for the parameter: b

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: a

Please provide descriptive name for the parameter: b

"""
Swap two integers using bitwise XOR operation and return the swapped values.

>>> xor_swap(5, 10)
(10, 5)
>>> xor_swap(0, 0)
(0, 0)
>>> xor_swap(-1, 1)
(1, -1)
>>> xor_swap(123, 456)
(456, 123)
>>> xor_swap(12345, 54321)
(54321, 12345)
"""
a = a ^ b
b = a ^ b
a = a ^ b
return a, b


if __name__ == "__main__":
import doctest

doctest.testmod()
Loading