- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
- Related Articles
- Check whether the bit at given position is set or unset in Python
- Position of rightmost common bit in two numbers in C++
- How do we check in Python whether a string contains only numbers?
- Find position of the only set bit in C++
- Check whether K-th bit is set or nots in Python
- Find position of left most dis-similar bit for two numbers in C++
- Program to find the indexes where the substrings of a string match with another string fully or differ at one position in python
- Check if given array is almost sorted (elements are at-most one position away) in Python
- Program to check whether every one has at least a friend or not in Python
- 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 given three numbers are adjacent primes in Python
- Check whether the given numbers are Cousin prime or not in Python
- Get value of the bit at a specific position in BitArray in C#
- Python Pandas - Check whether two Interval objects overlap

Advertisements