Techieindoor

Leetcode 693: Binary Number with Alternating Bits

Here, we will help to understand about how to solve Binary Number with Alternating Bits solution of leet code 693 with code and algorithm.

You are given a positive integer. You have to check whether it has alternating bits or not. It means two adjacent bits will always have different values.

Example:

1)
Input: n = 10
Output: true
Explanation: The binary representation of 10 is: 1010
Here, adjacent bits are difference i.e 1 then 0 then 1 then 0 (1 -> 0 -> 1 -> 0)

2)
Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111
Here, adjacent bits are not difference i.e 1 then again 1 then again 1 (1 -> 1 -> 1 -> 1)

3)
Input: n = 15
Output: false
Explanation: The binary representation of 15 is: 1111
Here, adjacent bits are not difference i.e 1 then again 1 then again 1 then again 1(1 -> 1 -> 1 -> 1 -> 1)

4)
Input: n = 21
Output: true
Explanation: The binary representation of 21 is: 10101

Algorithm 1:

Binary Number with Alternating Bits code in C++

Code 1:

#include <iostream>

using namespace std;

bool hasAlternatingBits(int n) {
    // Get the first bit
    int prev_bit = n & 1;
    n >>= 1;
        
    while(n) {
        // Compare prev_bit with current bit.
        if(prev_bit == (n & 1)) {
            
            // If both are equal then return false 
            return false;
        }
        prev_bit = n & 1;
        n >>= 1;
    }
    return true;
}

int main()
{
    cout<<hasAlternatingBits(10);

    return 0;
}

Code 2:

#include <iostream>

using namespace std;

bool hasAlternatingBits(int n) {
    int l = n % 2;

    n >>= 1;
    
    while (n > 0)
    {
        int current = n % 2;
        if (l == current)
            return (false);
        l = current;
        n >>= 1;
    }
    return true;
}

int main()
{
    cout<<hasAlternatingBits(10);

    return 0;
}

Code 3:

#include <iostream>

using namespace std;

bool hasAlternatingBits(int n) {
        
    int store=2;
        
    while(n) {
            
        if((n%2)==store)
            return 0;
        else
            store=n%2;
            
        n/=2;
            
    }
    return 1;
}

int main()
{
    cout<<hasAlternatingBits(10);

    return 0;
}

Output:

Input: 10 in bit's: 1010
Output: 1 i.e (true)

To check more leetcode problem’s solution. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

Exit mobile version