# Check if one of the numbers is one’s complement of the other in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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.

To solve this, we will follow these steps −

• z = x XOR y
• return true when all bits in z are set, otherwise false

## Example

Let us see the following implementation to get better understanding −

Live Demo

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

## Input

9, 6

## Output

True