题目:
Given an integer, write a function to determine if it is a power of two.
思考:
2是一个比较特殊的数,可以利用二进制来解决此问题。
方法一:性能45ms
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n < 0:
return False
m = bin(n)
s = m[2:]
return m.count('1') == 1
方法二:性能39ms
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n>0 and not (n&n-1)