Check if one of the numbers is one’s complement of the other
Last Updated :
15 Jul, 2022
Given two non-negative integers a and b. The problem is to check if one of the two numbers is 1’s complement of the other.
The ones’ complement of a binary number is defined as the value obtained by inverting all the bits in the binary representation of the number (swapping 0s for 1s and vice versa).
Examples:
Input : a = 10, b = 5
Output : Yes
(10)10 = (1010)2
1's complement of 10 is
= (0101)2 = (101)2 = (5)10
Input : a = 1, b = 14
Output : Yes
(14)10 = (1110)2
1's complement of 14 is
= (0001)2 = (1)2 = (1)10
Approach: Following are the steps:
- Calculate n = a ^ b.
- Check whether all bits are set in the binary representation of n. Refer to this post.
CPP
#include <bits/stdc++.h>
using namespace std;
bool areAllBitsSet(unsigned int n)
{
if (n == 0)
return false ;
if (((n + 1) & n) == 0)
return true ;
return false ;
}
bool isOnesComplementOfOther(unsigned int a,
unsigned int b)
{
return areAllBitsSet(a ^ b);
}
int main()
{
unsigned int a = 10, b = 5;
if (isOnesComplementOfOther(a,b))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
public class GfG{
public static boolean areAllBitsSet( long n)
{
if (n == 0 )
return false ;
if (((n + 1 ) & n) == 0 )
return true ;
return false ;
}
public static boolean isOnesComplementOfOther( long a,
long b)
{
return areAllBitsSet(a ^ b);
}
public static void main(String argc[]){
long a = 10 , b = 5 ;
if (isOnesComplementOfOther(a,b))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def areAllBitsSet(n):
if (n = = 0 ):
return False ;
if (((n + 1 ) & n) = = 0 ):
return True ;
return False ;
def isOnesComplementOfOther(a, b):
return areAllBitsSet(a ^ b)
a = 1
b = 14
if (isOnesComplementOfOther(a, b)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
public static bool areAllBitsSet( long n)
{
if (n == 0)
return false ;
if (((n + 1) & n) == 0)
return true ;
return false ;
}
public static bool isOnesComplementOfOther( long a,
long b)
{
return areAllBitsSet(a ^ b);
}
public static void Main()
{
long a = 10, b = 5;
if (isOnesComplementOfOther(a, b))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
PHP
<?php
function areAllBitsSet( $n )
{
if ( $n == 0)
return false;
if ((( $n + 1) & $n ) == 0)
return true;
return false;
}
function isOnesComplementOfOther( $a ,
$b )
{
return areAllBitsSet( $a ^ $b );
}
$a = 10; $b = 5;
if (isOnesComplementOfOther( $a , $b ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function areAllBitsSet(n)
{
if (n == 0)
return false ;
if (((n + 1) & n) == 0)
return true ;
return false ;
}
function isOnesComplementOfOther(a, b)
{
return areAllBitsSet(a ^ b);
}
let a = 10, b = 5;
if (isOnesComplementOfOther(a,b))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Output:
Yes
Time Complexity : O(1)
Auxiliary Space : O(1)
Share your thoughts in the comments
Please Login to comment...