C++ Program to Check if Number is Power of 2
(n > 0) && ((n & (n - 1)) == 0), which returns true if n is a power of 2.Examples
How to Think About It
AND between the number and one less than it will be zero only if the number is a power of 2.Algorithm
Code
#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; }
Dry Run
Let's trace the number 16 through the code to see how it checks if it is a power of 2.
Input number
n = 16
Check if n > 0
16 > 0 is true
Calculate n - 1
16 - 1 = 15
Bitwise AND operation
16 & 15 = 0 (binary 10000 & 01111 = 00000)
Check if result is 0
Result is 0, so 16 is a power of 2
| n | n-1 | n & (n-1) |
|---|---|---|
| 16 | 15 | 0 |
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
#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; }
#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; }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bitwise AND | O(1) | O(1) | Fastest and simplest check |
| Loop Division | O(log n) | O(1) | Easy to understand, slower for large numbers |
| Logarithm | O(1) | O(1) | Mathematical approach, may have precision issues |
(n & (n - 1)) == 0 for a fast and simple power of 2 test.