
递归法:
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n==1:
return True
if n<=0 or n%2!=0:
return False
return self.isPowerOfTwo(n/2)
循环法:
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n<=0:
return False
for i in range(0,n):
if 2**i==n:
return True
if 2**i>n:
return False
break
位运算法(二进制):
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
# 转为二进制字符串
bs = bin(n)
if bs[2]=='1' and '1' not in bs[3:]:
return True
else:
return False
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
# 位运算
if n>0 and (n&-n)==n:
return True
else:
return False
© 版权声明
若无特殊说明,文章版权归作者所有,请勿转载至任何平台。
THE END
暂无评论内容