Question
Given an integer, write a function to determine if it is a power of two.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Show Tags
Show Similar Problems
Solution
Time complexity: O(logn)
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n==0:
return False
if n==1:
return True
while n%2==0:
n /= 2
if n==1:
return True
return False
Time complexity: O(1)
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n>0 and n&(n-1)==0