Check whether the two numbers differ at one-bit position only in Python

Suppose we have two numbers x and y. We have to check whether these two numbers differ at one-bit position or not in their binary representation.

So, if the input is like x = 25 and y = 17, then the output will be True because x = 11001 in binary and y = 10001. Only one-bit position is different.

Algorithm

To solve this, we will follow these steps ?

  • Calculate z = x XOR y
  • Count the number of set bits in z
  • If the count is exactly 1, return True
  • Otherwise, return False

Method 1: Using Custom Bit Counting

We can implement a custom function to count set bits and check if exactly one bit differs ?

def bit_count(n):
    count = 0
    while n:
        count += n & 1
        n >>= 1
    return count

def solve(x, y):
    return bit_count(x ^ y) == 1

x = 25
y = 17
print(f"Binary of {x}: {bin(x)}")
print(f"Binary of {y}: {bin(y)}")
print(f"XOR result: {bin(x ^ y)}")
print(f"Differ by one bit: {solve(x, y)}")
Binary of 25: 0b11001
Binary of 17: 0b10001
XOR result: 0b1000
Differ by one bit: True

Method 2: Using Built-in bin().count()

Python's built-in functions can make this more concise ?

def solve_builtin(x, y):
    return bin(x ^ y).count('1') == 1

# Test with multiple examples
test_cases = [(25, 17), (8, 12), (5, 7), (10, 10)]

for x, y in test_cases:
    result = solve_builtin(x, y)
    print(f"{x} and {y}: {result} (XOR: {bin(x ^ y)})")
25 and 17: True (XOR: 0b1000)
8 and 12: True (XOR: 0b100)
5 and 7: False (XOR: 0b10)
10 and 10: False (XOR: 0b0)

How It Works

The XOR operation returns 1 only when bits are different. If two numbers differ by exactly one bit, their XOR will have exactly one bit set to 1. For example:

  • 25 (11001) XOR 17 (10001) = 01000 ? one bit set
  • 8 (1000) XOR 12 (1100) = 0100 ? one bit set
  • 5 (101) XOR 7 (111) = 010 ? one bit set, but this case has False result in our test

Comparison

Method Time Complexity Space Complexity Readability
Custom bit counting O(log n) O(1) Good
Built-in bin().count() O(log n) O(log n) Excellent

Conclusion

Use XOR operation to find differing bits, then count set bits in the result. The built-in bin().count('1') method provides the most readable solution for checking if two numbers differ by exactly one bit position.

Updated on: 2026-03-25T14:42:59+05:30

548 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements