Check if a number has two adjacent set bits
Last Updated :
15 Jul, 2022
Given a number you have to check whether there is pair of adjacent set bit or not.
Examples :
Input : N = 67
Output : Yes
There is a pair of adjacent set bit
The binary representation is 100011
Input : N = 5
Output : No
A simple solution is to traverse all bits. For every set bit, check if next bit is also set.
An efficient solution is to shift number by 1 and then do bitwise AND. If bitwise AND is non-zero then there are two adjacent set bits. Else not.
C++
#include <iostream>
using namespace std;
bool adjacentSet( int n)
{
return (n & (n >> 1));
}
int main()
{
int n = 3;
adjacentSet(n) ?
cout << "Yes" :
cout << "No" ;
return 0;
}
|
Java
class GFG
{
static boolean adjacentSet( int n)
{
int x = (n & (n >> 1 ));
if (x > 0 )
return true ;
else
return false ;
}
public static void main(String args[])
{
int n = 3 ;
if (adjacentSet(n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def adjacentSet(n):
return (n & (n >> 1 ))
if __name__ = = '__main__' :
n = 3
if (adjacentSet(n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool adjacentSet( int n)
{
int x = (n & (n >> 1));
if (x > 0)
return true ;
else
return false ;
}
public static void Main ()
{
int n = 3;
if (adjacentSet(n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
php
<?php
function adjacentSet( $n )
{
return ( $n & ( $n >> 1));
}
$n = 3;
adjacentSet( $n ) ?
print ( "Yes" ) :
print ( "No" );
?>
|
Javascript
<script>
function adjacentSet(n)
{
let x = (n & (n >> 1));
if (x > 0)
return true ;
else
return false ;
}
let n = 3;
if (adjacentSet(n))
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...