Bitwise Operators: Given a number, check if it has 2 adjacent set bits

Example:

Input N = 5

Output No

Solution :

Solution is very simple.

Traverse all bits.

For every set bits, check if next bit is also set.

Another solution is to shift the number by 1 and then do bitwise AND.
If the result is non zero then there are 2 adjacent bits, else not.

Time Complexity: O(1)
Space Complexity: O(1)

Code Solution


#include <iostream>
#include <bits/stdc++.h>

using namespace std;

bool solution_1(int n)
{
    return (n & (n >> 1)); 

}

int main()
{

    int n = 3;
    
    if (solution_1(n))
        cout << "Yes" << endl;
    else
        cout << "No";
    

    return 0;
}

Output

Yes
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *