2^x | n | n - 1 | n & (n - 1) |
---|---|---|---|
2^0 | 0001 | 0000 | (0001) & (0000) == 0 |
2^1 | 0010 | 0001 | (0010) & (0001) == 0 |
2^2 | 0100 | 0011 | (0100) & (0011) == 0 |
2^3 | 1000 | 0111 | (1000) & (0111) == 0 |
class Solution:
def isPowerOfTwo(self, n):
return n > 0 and n & (n - 1) == 0