0
0
CppProgramBeginner · 2 min read

C++ Program to Check if Number is Power of 2

In C++, you can check if a number is a power of 2 by using the expression (n > 0) && ((n & (n - 1)) == 0), which returns true if n is a power of 2.
📋

Examples

Input16
Output16 is a power of 2
Input18
Output18 is not a power of 2
Input1
Output1 is a power of 2
🧠

How to Think About It

To check if a number is a power of 2, think about its binary form. A power of 2 has exactly one '1' bit and the rest are '0's. By subtracting 1 from the number, all bits after that single '1' become '1's. Using AND between the number and one less than it will be zero only if the number is a power of 2.
📐

Algorithm

1
Get the input number n
2
Check if n is greater than 0
3
Perform bitwise AND between n and (n - 1)
4
If the result is 0, then n is a power of 2
5
Otherwise, n is not a power of 2
6
Print the result
💻

Code

cpp
#include <iostream>
using namespace std;

bool isPowerOfTwo(int n) {
    return (n > 0) && ((n & (n - 1)) == 0);
}

int main() {
    int n;
    cout << "Enter a number: ";
    cin >> n;
    if (isPowerOfTwo(n))
        cout << n << " is a power of 2" << endl;
    else
        cout << n << " is not a power of 2" << endl;
    return 0;
}
Output
Enter a number: 16 16 is a power of 2
🔍

Dry Run

Let's trace the number 16 through the code to see how it checks if it is a power of 2.

1

Input number

n = 16

2

Check if n > 0

16 > 0 is true

3

Calculate n - 1

16 - 1 = 15

4

Bitwise AND operation

16 & 15 = 0 (binary 10000 & 01111 = 00000)

5

Check if result is 0

Result is 0, so 16 is a power of 2

nn-1n & (n-1)
16150
💡

Why This Works

Step 1: Check positive number

The number must be greater than 0 because powers of 2 are positive.

Step 2: Bitwise AND trick

Using n & (n - 1) clears the lowest set bit. If the result is 0, only one bit was set.

Step 3: Result means power of 2

If only one bit is set, the number is a power of 2, so return true.

🔄

Alternative Approaches

Loop division
cpp
#include <iostream>
using namespace std;

bool isPowerOfTwo(int n) {
    if (n <= 0) return false;
    while (n % 2 == 0) {
        n /= 2;
    }
    return n == 1;
}

int main() {
    int n;
    cout << "Enter a number: ";
    cin >> n;
    if (isPowerOfTwo(n))
        cout << n << " is a power of 2" << endl;
    else
        cout << n << " is not a power of 2" << endl;
    return 0;
}
This method divides the number by 2 repeatedly and checks if the final result is 1. It is easy to understand but slower than bitwise.
Using logarithm
cpp
#include <iostream>
#include <cmath>
using namespace std;

bool isPowerOfTwo(int n) {
    if (n <= 0) return false;
    double logVal = log2(n);
    return floor(logVal) == logVal;
}

int main() {
    int n;
    cout << "Enter a number: ";
    cin >> n;
    if (isPowerOfTwo(n))
        cout << n << " is a power of 2" << endl;
    else
        cout << n << " is not a power of 2" << endl;
    return 0;
}
This method uses logarithms to check if the log base 2 is an integer. It involves floating-point operations and may have precision issues.

Complexity: O(1) time, O(1) space

Time Complexity

The bitwise operation runs in constant time because it uses a fixed number of CPU instructions regardless of input size.

Space Complexity

The program uses constant space as it only stores a few variables and does not allocate extra memory.

Which Approach is Fastest?

The bitwise method is fastest and simplest compared to loop division or logarithm methods, which are slower or less precise.

ApproachTimeSpaceBest For
Bitwise ANDO(1)O(1)Fastest and simplest check
Loop DivisionO(log n)O(1)Easy to understand, slower for large numbers
LogarithmO(1)O(1)Mathematical approach, may have precision issues
💡
Use the bitwise check (n & (n - 1)) == 0 for a fast and simple power of 2 test.
⚠️
Forgetting to check if the number is greater than zero before applying the bitwise test causes incorrect results for zero or negative numbers.