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.

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
raja
Published on 27-Sep-2019 09:02:54
Advertisements