[
math
bit manipulation
]
Leetcode 0231. Power of Two
https://leetcode.com/problems/power-of-two
This is classical bit manipulation problem for n & (n-1)
trick, which removes the last non-zero bit from our number
example:
1.n = 100000
, then n - 1 = 011111
and n & (n-1) = 000000
, so if it is power of two, result is zero
2.n = 101110
, then n - 1 = 101101
and n & (n-1) = 101100
, number is not power of two and result is not zero.
class Solution:
def isPowerOfTwo(self, n):
return n > 0 and not (n & n-1)
Update there is another O(1)
solution using math: number is power of 2
if it is divisor of the biggest possible power of 2
:
return n > 0 and (1<<32) % n == 0
If you like the solution, you can upvote it on leetcode discussion section: Problem 0231