Welcome to DailyCodeHub.
If you are learning Python or preparing for coding interviews, you might have come across the swapping problem. But sometimes interviewers ask a slightly different variation—swap two numbers using the bitwise XOR operator.
At first this looks confusing especially if you are not familiar with bitwise operations. however once you understand the logic behind XOR the concept becomes simple and interesting.
This type of question is commonly asked in interviews to test your understanding of low-level operations and how values are handled internally in programming.
I personally recommend trying this method step by step. when you execute the code yourself, you will clearly see how the values change without using any extra variable.
In this article we will learn how to swap two numbers in Python using the bitwise XOR operator without using a temporary variable.
Before we start - basics :
Swapping means exchanging the values of two variables.
For example :
a = 5 and b = 10
After swapping :
a = 10 and b = 5
In this method we use the XOR (^) operator instead of arithmetic or tuple methods.
Question :
Write a Python program to swap two integers using bitwise XOR.
Method: Using XOR operator
Code:
# Author: P.Prabhas
# Function to swap numbers using XOR
def swap_xor(a, b):
# Swap using XOR
a = a ^ b
b = a ^ b
a = a ^ b
return a, b
# Take input from user
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
# Print before swapping
print("Before swapping:", a, b)
# Call function
a, b = swap_xor(a, b)
# Print after swapping
print("After swapping:", a, b)
Output:
Enter first number: 5
Enter second number: 10
Before swapping: 5 10
After swapping: 10 5
How it works :
Let's take an example: a = 5 and b = 10
Let us see how values change step by step :
step 1:
a = a ^ b
step 2:
b = a ^ b
step 3:
a = a ^ b
Final result : a = 10, b = 5 (values swapped)
Example with actual values :
a = 5, b = 10
a = a ^ b → 5 ^ 10 = 15
b = a ^ b → 15 ^ 10 = 5
a = a ^ b → 15 ^ 5 = 10
Final result : a = 10, b = 5
In this method XOR combines and restores values. when we apply XOR multiple times it helps us retrieve the original values without using any extra variable.
Simple idea : XOR mixes the values and then brings them back step by step.
Important concept behind XOR :
The XOR operator follows a simple rule:
X ^ Y ^ Y = X
This means if we apply XOR twice with the same value, we get the original number back.
That is why this method works without needing a temporary variable.
Key points :
- NO extra variable is used
- Works using bitwise operations
- Useful for understanding low-level logic
- Common interview question
- Helps improve problem-solving skills

No comments:
Post a Comment