Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
A positive power of two has exactly one set bit. Subtracting one clears its lowest set bit and turns all lower zero bits into ones. Consequently, n & (n - 1) removes the lowest set bit from any positive integer and becomes zero exactly when no other set bit exists.
Approach
- Reject zero and negative values; neither can be a power of two under this definition.
- Compute the bitwise AND of
nandn - 1. - Return whether that value is zero. The positivity check is essential because zero also satisfies the bitwise equality. The value one is accepted, representing
2^0.
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n <= 0:
return False
return not (n & n - 1)Complexity analysis
The single bit test uses O(1) time and O(1) auxiliary space.
