Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if one of the numbers is one's complement of the other in Python
Suppose we have two numbers x and y. We have to check whether one of these two numbers is 1's complement of the other or not. We all know the 1's complement of a binary number is flipping all bits from 0 to 1 or 1 to 0.
So, if the input is like x = 9, y = 6, then the output will be True as the binary representations are x = 1001 and y = 0110 which are complement of each other.
Algorithm
To solve this, we will follow these steps ?
- Calculate z = x XOR y
- Return true when all bits in z are set, otherwise false
The key insight is that if two numbers are one's complement of each other, their XOR will result in a number with all bits set (like 1111 in binary).
Implementation
def all_one(n):
if n == 0:
return False
if ((n + 1) & n) == 0:
return True
return False
def solve(x, y):
return all_one(x ^ y)
x = 9
y = 6
print(solve(x, y))
True
How It Works
Let's trace through the example step by step ?
x = 9 # Binary: 1001
y = 6 # Binary: 0110
# XOR operation
xor_result = x ^ y
print(f"x = {x} (binary: {bin(x)})")
print(f"y = {y} (binary: {bin(y)})")
print(f"x ^ y = {xor_result} (binary: {bin(xor_result)})")
# Check if all bits are set
print(f"All bits set? {((xor_result + 1) & xor_result) == 0}")
x = 9 (binary: 0b1001) y = 6 (binary: 0b0110) x ^ y = 15 (binary: 0b1111) All bits set? True
Additional Examples
def all_one(n):
if n == 0:
return False
return ((n + 1) & n) == 0
def solve(x, y):
return all_one(x ^ y)
# Test different cases
test_cases = [(9, 6), (5, 2), (3, 4), (7, 0)]
for x, y in test_cases:
result = solve(x, y)
print(f"x={x} ({bin(x)}), y={y} ({bin(y)}) ? {result}")
x=9 (0b1001), y=6 (0b0110) ? True x=5 (0b101), y=2 (0b10) ? True x=3 (0b11), y=4 (0b100) ? False x=7 (0b111), y=0 (0b0) ? True
Key Points
- The XOR of two one's complement numbers produces a number with all bits set
- A number has all bits set if
(n + 1) & n == 0 - This works because adding 1 to a number with all bits set causes overflow
Conclusion
To check if two numbers are one's complement of each other, XOR them and verify if the result has all bits set. This approach efficiently determines the complement relationship using bitwise operations.
