231. Power of Two
Easy ↗ Open on LeetCode Source: Misc
Quick review
- Pattern
- Bit Manipulation
- Time
- O(1)
- Space
- O(1)
Standard Solution (C++)
SummaryGiven an integer n, determine whether it is an exact power of two (i.e., equals 2^k for some non-negative integer k). Return true if so, false otherwise.
Approach
- A positive power of two has exactly one bit set in its binary representation (e.g., 8 =
1000). - The classic bit trick
n & (n - 1)clears the lowest set bit of n; if the result is zero, n had exactly one bit set. - We also guard against
n <= 0because zero and negative numbers are never powers of two, andn - 1wraps problematically for n = 0. - The entire check is a single bitwise AND and comparison, making it branchless and O(1).
#include <iostream>
using namespace std;
class Solution {
public:
// A power of two has exactly one bit set: n & (n-1) clears that bit.
// The result is 0 iff n was a power of two; guard n > 0 to exclude 0/negatives.
bool isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
}; Time O(1) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
bool isPowerOfTwo(int n) {
// if n is 2^k, then only 1 bit is 1
return n>0 && (n&(n-1))==0;
}
};
// Time Complexity: O(1)
// Space Complexity: O(1) Time O(1) Space O(1)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.