Python Program to swap two numbers using xor

Program

a = int(input("Enter the value of a:\n"))
b = int(input("Enter the value of b:\n"))
print("Values before swapping:")
print("a:\t{}\nb:\t{}".format(a,b))
a = a ^ b
b = a ^ b
a = a ^ b
print("Values after swapping:")
print("a:\t{}\nb:\t{}".format(a,b))

This program swaps two numbers without using a temporary variable, instead utilizing the XOR bitwise operator (^).

a = int(input("Enter the value of a:\n"))
b = int(input("Enter the value of b:\n"))
  • The user inputs two numbers (a and b).
  • input() takes input as a string, and int() converts it to an integer.
print("Values before swapping:")
print("a:\t{}\nb:\t{}".format(a, b))
  • Displays the original values before swapping.

Swapping Logic Using XOR:

a = a ^ b  # Step 1: XOR the two numbers and store in 'a'
b = a ^ b  # Step 2: XOR 'a' (new value) with 'b', which restores 'a' to its original value and stores in 'b'
a = a ^ b  # Step 3: XOR 'a' (new value) with 'b' (original 'a'), swapping the values

How XOR Works for Swapping:
The XOR operation follows these rules:

  • 0 ^ 0 = 0
  • 1 ^ 1 = 0
  • 0 ^ 1 = 1
  • 1 ^ 0 = 1

So, when we apply a = a ^ b, it stores the XOR result of a and b in a.

  • b = a ^ b then restores a's original value to b.
  • a = a ^ b restores b's original value to a.

No extra variable is needed!

print("Values after swapping:")
print("a:\t{}\nb:\t{}".format(a, b))
  • Prints the swapped values.

Key Takeaways:

No temporary variable required.

  • Uses bitwise XOR (^) for swapping.
  • Works efficiently on integer values.
  • Faster in low-level programming but not as readable as traditional methods.

Output

Enter the value of a:
31
Enter the value of b:
89
Values before swapping:
a:	31
b:	89
Values after swapping:
a:	89
b:	31