Check if a number has two adjacent set bits in C++

C++Server Side ProgrammingProgramming

Here we will see, if a number has adjacent set bits in its binary representation. Suppose the number 12 has two consecutive 1s (12 = 1100).

To check this type of number, the idea is very simple. We will shift the number 1 bit, then do bitwise AND. If the bitwise AND result is non-zero, then there must be some consecutive 1s.


 Live Demo

#include <iostream>
using namespace std;
bool hasConsecutiveOnes(int n) {
   if((n & (n >> 1)) == 1){
   return true;
      return false;
int main() {
   int num = 67; //1000011
      cout << "Has Consecutive 1s";
      cout << "Has No Consecutive 1s";


Has Consecutive 1s
Published on 27-Sep-2019 09:02:54