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


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.

Example

 Live Demo

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

Output

Has Consecutive 1s

Updated on: 27-Sep-2019

442 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements