Power of Two
Given an integer, write a function to determine if it is a power of two.
题目大意:
给定一个整数,编写函数判断它是否是2的幂。
解题思路:
如果一个整数是2的幂,那么它的二进制形式最高位为1,其余各位为0
等价于:n & (n - 1) = 0,且n > 0
Python代码:
return n > 0 and n & (n - 1) == 0
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
while n and n%2==0:
n=n/2
if n==1:
return True
return False
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n>0 and (math.log10(n)/math.log10(2))%1 == 0
Last updated
Was this helpful?