Check whether the two numbers differ at one bit position only
Last Updated :
15 Jun, 2022
Given two non-negative integers a and b. The problem is to check whether the two numbers differ at one bit position only or not.
Examples:
Input : a = 13, b = 9
Output : Yes
(13)10 = (1101)2
(9)10 = (1001)2
Both the numbers differ at one bit position only, i.e,
differ at the 3rd bit from the right.
Input : a = 15, b = 8
Output : No
Approach: Following are the steps:
- Calculate num = a ^ b.
- Check whether num is a power of 2 or not. Refer this post.
C++
#include <bits/stdc++.h>
using namespace std;
bool isPowerOfTwo(unsigned int x)
{
return x && (!(x & (x - 1)));
}
bool differAtOneBitPos(unsigned int a,
unsigned int b)
{
return isPowerOfTwo(a ^ b);
}
int main()
{
unsigned int a = 13, b = 9;
if (differAtOneBitPos(a, b))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static boolean isPowerOfTwo( int x)
{
return x!= 0 && ((x & (x - 1 )) == 0 );
}
static boolean differAtOneBitPos( int a, int b)
{
return isPowerOfTwo(a ^ b);
}
public static void main(String args[])
{
int a = 13 , b = 9 ;
if (differAtOneBitPos(a, b) == true )
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def isPowerOfTwo( x ):
return x and ( not (x & (x - 1 )))
def differAtOneBitPos( a , b ):
return isPowerOfTwo(a ^ b)
a = 13
b = 9
if (differAtOneBitPos(a, b)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool isPowerOfTwo( int x)
{
return x != 0 && ((x & (x - 1)) == 0);
}
static bool differAtOneBitPos( int a, int b)
{
return isPowerOfTwo(a ^ b);
}
public static void Main()
{
int a = 13, b = 9;
if (differAtOneBitPos(a, b) == true )
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function isPowerOfTwo( $x )
{
$y = 0;
if ( $x && (!( $x & ( $x - 1))))
$y = 1;
return $y ;
}
function differAtOneBitPos( $a , $b )
{
return isPowerOfTwo( $a ^ $b );
}
$a = 13;
$b = 9;
if (differAtOneBitPos( $a , $b ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function isPowerOfTwo(x)
{
return x!= 0 && ((x & (x - 1)) == 0);
}
function differAtOneBitPos(a, b)
{
return isPowerOfTwo(a ^ b);
}
let a = 13, b = 9;
if (differAtOneBitPos(a, b) == true )
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...