Binary Number with Alternating Bits in C++


Suppose we have a positive integer, we have to check whether it has alternating bits − so, two adjacent bits will always have different values.

So, if the input is like 10, then the output will be True, as binary representation of 10 is 1010.

To solve this, we will follow these steps −

  • p := n AND 1
  • if n < 2, then −
    • return true
  • n := n/2
  • while n is non-zero, do −
    • c := n AND 1
    • if c XOR p is same as 0, then −
      • return false
    • p := c
    • n := n/2
  • return true

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool hasAlternatingBits(int n) {
      bool p=n&1;
      bool c;
      if(n<2)
         return true;
      n>>=1;
      while(n){
         c=n&1;
         if(c^p==0)
            return false;
         p=c;
         n>>=1;
      }
      return true;
   }
};
main(){
   Solution ob;
   cout << (ob.hasAlternatingBits(10));
}

Input

10

Output

1

Updated on: 04-Jul-2020

362 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements