【递归】2的幂

1709253714352.webp

递归法:

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

https://leetcode.cn/problems/power-of-two/

© 版权声明
THE END
点赞11 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片快捷回复

    暂无评论内容