日野弥生:勉強しよう
LeetCode 231 - 2的幂
发表于2025年02月04日
递归法可以处理。
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 0:
return False
if n == 1:
return True
if n % 2 != 0:
return False
else:
# python3中的类方法递归的写法
return self.isPowerOfTwo(n / 2)
也可以利用python3的math接口直接求对数是否为整数来判断。
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
# 小于等于0的数全部判否
if n <= 0:
return False
#判断对数结果是否为整数
return math.log2(n).is_integer()