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

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

The expression (n & (n << 1) or (n & (n >> 1) will return 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))

## C++

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <bitset> using namespace std; // return true if adjacent bits are set in binary representation of n bool check(int n) { return n & (n << 1); } // Check if adjacent bits are set in binary representation of a given number int main() { int n = 67; cout << n << " in binary is " << bitset<8>(n) << endl; if (check(n)) cout << "Adjacent pair of set bits found"; else cout << "No adjacent pair of set bits found"; return 0; } |

`Output:`

67 in binary is 01000011

Adjacent pair of set bits found

**Read More –**

Bit Hacks – Part 1 (Basic)

Bit Hacks – Part 2 (Playing with k’th bit)

Bit Hacks – Part 3 (Playing with rightmost set bit of a number)

Bit Hacks – Part 4 (Playing with letters of English alphabet)

Bit Hacks – Part 5 (Find absolute value of an integer without branching)

**Suggested Read: **https://graphics.stanford.edu/~seander/bithacks.html

**Thanks for reading.**

Please use our online compiler to post code in comments. To contribute, get in touch with us.

Like us? Please spread the word and help us grow. Happy coding 🙂

## Leave a Reply