Given a number, check if adjacent bits are set in the binary representation of it.

Practice this problem

A naive solution is to consider every bit present in the number one by one and compare it with its previous bit. If the current bit is the same as the previous bit, we have found a pair whose adjacent bits are 1.

 
The expression n & (n << 1) or n & (n >> 1) returns true if n contains any pair whose adjacent bits are 1. For example,

00101101    &               (n)
01011010                    left shift n by 1
~~~~~~~~
00001000                    (n & (n << 1))

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

67 in binary is 01000011
Adjacent pair of set bits found

Java


Download  Run Code

Output:

67 in binary is 1000011
Adjacent pair of set bits found

Python


Download  Run Code

Output:

67 in binary is 0b1000011
Adjacent pair of set bits found

 
Also See:

Bit Hacks – Part 1 (Basic)
Bit Hacks – Part 2 (Playing with k’th bit)
Bit Hacks – Part 3 (Playing with the rightmost set bit of a number)
Bit Hacks – Part 4 (Playing with letters of the English alphabet)
Bit Hacks – Part 5 (Find the absolute value of an integer without branching)

 
Suggested Read:

https://graphics.stanford.edu/~seander/bithacks.html