Power of Two
Easy · Bit Manipulation · Explanation and code example
Math
How it works
The largest power of two that fits in a 32-bit signed integer is 2^30 (since 2^31 exceeds the positive range). Any smaller power of two must divide evenly into 2^30.
If n is a power of two, then 2^30 mod n equals 0. If n is not a power of two, the division will have a remainder.
Steps
- Check that
nis positive. - Compute
(1 << 30) % n(i.e.,2^30 mod n). - Return
trueif the result is0.
Complexity
- Time complexity:
O(1) - Space complexity:
O(1)
Things to watch for
Forgetting to Handle Non-Positive Numbers
A common mistake is forgetting that n must be strictly positive. Zero and negative numbers cannot be powers of two, but the bit manipulation tricks like n & (n - 1) == 0 will incorrectly return true for n = 0. Always check n > 0 before applying bit operations.
Integer Overflow in Iterative Approaches
When iteratively multiplying by 2 (e.g., x *= 2), the variable can overflow if using a 32-bit integer type. In languages like Java or C++, use a long or long long type for the accumulator to avoid wrapping around to negative values before reaching large inputs like 2^30.
Python code example
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and ((1 << 30) % n) == 0
C++ code example
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && ((1 << 30) % n) == 0;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.