- Related Questions & Answers
- Check whether the bit at given position is set or unset in Python
- Position of rightmost common bit in two numbers in C++
- Find position of the only set bit in C++
- How do we check in Python whether a string contains only numbers?
- Find position of left most dis-similar bit for two numbers in C++
- Program to check whether every one has at least a friend or not in Python
- Check if given array is almost sorted (elements are at-most one position away) in Python
- Python program to check if two lists have at least one common element
- Check whether K-th bit is set or nots in Python
- Get value of the bit at a specific position in BitArray in C#
- Check whether the number formed by concatenating two numbers is a perfect square or not in Python
- Check whether the number has only first and last bits set in Python
- Check whether the given numbers are Cousin prime or not in Python
- Set the bit at a specific position in the BitArray to the specified value in C#?
- Check whether the String contains only digit characters in Java

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

25,17

True

Advertisements