Check if a number has bits in alternate pattern - Set-2 O(1) Approach in C++


Let us consider we have an integer n. The problem is to check, whether this integer has alternate patterns in its binary equivalent or not. The alternate pattern means 101010….

The approach is like: calculate num = n XOR (n >> 1), now if all bits of num is 1, then the num has alternating patterns.

Example

 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
bool isAllBitSet(int n){
   if (((n + 1) & n) == 0)
      return true;
   return false;
}
bool hasAlternatePattern(unsigned int n) {
   unsigned int num = n ^ (n >> 1);
   return isAllBitSet(num);
}
int main() {
   unsigned int number = 42;
   if(hasAlternatePattern(number))
      cout << "Has alternating pattern";
   else
      cout << "Has no alternating pattern";
}

Output

Has alternating pattern

Updated on: 21-Oct-2019

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements