日野弥生:勉強しよう

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()

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/power-of-two/

上一篇

LeetCode 1512 - 好数对的数目

下一篇

LeetCode 138 - 随机链表的复制