Given an integer n
, write a function to determine if it is a power of two. A power of two is a number of the form (2^x) where x
is an integer.
n
?
n
will be a 32-bit signed integer, so it can range from -2,147,483,648 to 2,147,483,647.False
for non-positive numbers (0 and negative numbers)?
False
.n
is positive. If it isn’t, we should return False
.(n & (n - 1)) == 0
to check for powers of two. This works because:
(n - 1)
flips all bits after the rightmost set bit (including the set bit itself).n
and (n - 1)
should result in 0
if n
is a power of two.n <= 0
, immediately return False
.def isPowerOfTwo(n: int) -> bool:
if n <= 0:
return False
return (n & (n - 1)) == 0
# Test cases
print(isPowerOfTwo(1)) # True (2^0)
print(isPowerOfTwo(16)) # True (2^4)
print(isPowerOfTwo(218)) # False
print(isPowerOfTwo(1024))# True (2^10)
print(isPowerOfTwo(0)) # False
print(isPowerOfTwo(-4)) # False
(n & (n - 1))
is done in constant time.This method is efficient and covers all edge cases as required.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?