I used a bitwise trick. A number is a power of two if:
- It is positive.
- It has exactly one bit set in its binary representation.
The property (n & (n - 1)) == 0 checks this, because subtracting 1 from a power of two flips the single 1 bit to 0 and sets all lower bits to 1, so the bitwise AND becomes 0. For any number that isn’t a power of two, this condition fails.
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n > 0 and (n & (n - 1)) == 0
- Time: O(1)
- Space: O(1)
