Python Program to Find XOR of Two Numbers
You can find the XOR of two numbers in Python using the
^ operator like this: result = a ^ b.Examples
Inputa = 5, b = 3
Output6
Inputa = 10, b = 10
Output0
Inputa = 0, b = 7
Output7
How to Think About It
To find the XOR of two numbers, think of comparing their bits. The XOR operator
^ returns 1 for each bit position where the bits of the two numbers differ, and 0 where they are the same. So, the result is a new number representing these differences.Algorithm
1
Get the first number as input.2
Get the second number as input.3
Apply the XOR operator <code>^</code> between the two numbers.4
Store the result.5
Return or print the result.Code
python
a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) result = a ^ b print("XOR of", a, "and", b, "is", result)
Output
Enter first number: 5
Enter second number: 3
XOR of 5 and 3 is 6
Dry Run
Let's trace the example where a = 5 and b = 3 through the code.
1
Input numbers
a = 5, b = 3
2
Apply XOR operator
5 in binary is 0101, 3 in binary is 0011; XOR is 0110 which is 6
3
Print result
Output: XOR of 5 and 3 is 6
| a (decimal) | b (decimal) | a (binary) | b (binary) | a ^ b (binary) | a ^ b (decimal) |
|---|---|---|---|---|---|
| 5 | 3 | 0101 | 0011 | 0110 | 6 |
Why This Works
Step 1: XOR operator basics
The ^ operator compares bits of two numbers and returns 1 if bits differ, else 0.
Step 2: Bitwise comparison
Each bit of the two numbers is compared independently to produce the result.
Step 3: Result formation
The resulting bits form a new number representing the XOR of the inputs.
Alternative Approaches
Using a function
python
def xor_two_numbers(x, y): return x ^ y print(xor_two_numbers(5, 3))
This approach makes the code reusable and clearer for multiple XOR operations.
Using bitwise operations manually
python
def manual_xor(x, y): result = 0 power = 1 while x > 0 or y > 0: bit_x = x % 2 bit_y = y % 2 xor_bit = (bit_x + bit_y) % 2 result += xor_bit * power x //= 2 y //= 2 power *= 2 return result print(manual_xor(5, 3))
This shows how XOR works bit by bit but is less efficient and more complex.
Complexity: O(1) time, O(1) space
Time Complexity
XOR operation is a single CPU instruction working on fixed-size integers, so it runs in constant time.
Space Complexity
No extra memory is needed besides a variable to store the result, so space is constant.
Which Approach is Fastest?
Using the built-in ^ operator is fastest and simplest compared to manual bitwise methods.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Using ^ operator | O(1) | O(1) | Simple and fast XOR |
| Function wrapper | O(1) | O(1) | Reusable code |
| Manual bitwise method | O(log n) | O(1) | Educational, bit-level understanding |
Use the
^ operator directly for simple and fast XOR calculations.Beginners often confuse XOR
^ with exponentiation ** in Python.