![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements