Check Power of 2 Using Bitwise

Check Power of 2 Using Bitwise

Hard C++ Operators 45 views
Explanation Complexity

Problem Statement

Check if number is power of 2 using single bitwise operation.
Real Life: Powers of 2 are special in computing (2, 4, 8, 16...).

Input Format

An integer N.

Output Format

Print

• Power of 2
OR

• Not a Power of 2

Example

16
Power of 2

Constraints

• N > 0

• Use single bitwise operation

Concept Explanation

A number is a power of 2 if it has only one bit set in binary.
Example:

• 8 = 1000

• 16 = 10000

Step-by-Step Explanation

1.Take input number N.

2.Check the condition:

• N & (N - 1)

3.If result is 0 and N > 0:

• It is a Power of 2.

4.Else:

• It is Not a Power of 2.

Concept Explanation

A number is a power of 2 if it has only one bit set in binary.
Example:

• 8 = 1000

• 16 = 10000

Step-by-Step Explanation

1.Take input number N.

2.Check the condition:

• N & (N - 1)

3.If result is 0 and N > 0:

• It is a Power of 2.

4.Else:

• It is Not a Power of 2.

Input / Output Format

Input Format
An integer N.
Output Format
Print

• Power of 2
OR

• Not a Power of 2
Constraints
• N > 0

• Use single bitwise operation

Examples

Input:
16
Output:
Power of 2

Example Solution (Public)

C++
void operator_q12_power_of_2() {
    int numbers[] = {16, 18, 32, 50, 64};
    
    for(int i = 0; i < 5; i++) {
        int num = numbers[i];
        if(num > 0 && (num & (num - 1)) == 0) {
            cout << num << " is power of 2" << endl;
        } else {
            cout << num << " is NOT power of 2" << endl;
        }
    }
}

Official Solution Code

void operator_q12_power_of_2() {
    int numbers[] = {16, 18, 32, 50, 64};
    
    for(int i = 0; i < 5; i++) {
        int num = numbers[i];
        if(num > 0 && (num & (num - 1)) == 0) {
            cout << num << " is power of 2" << endl;
        } else {
            cout << num << " is NOT power of 2" << endl;
        }
    }
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.