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.

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

To solve this, we will follow these steps −

  • z = x XOR y
  • if number of set bits in z is 1, then
    • return True
  • return False

Let us see the following implementation to get better understanding −

Example Code

Live Demo

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(solve(x, y))

Input

25,17

Output

True

Updated on: 16-Jan-2021

289 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements