首页 > 其他 > 详细

leetcode-231-2的幂

时间:2019-10-05 17:31:06      阅读:74      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

第一次提交:

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        if n==0:return False
        if n==1:
            return True
        s = str(bin(n))[3:]
        for i in s:
            if i == 1:
                return False
        return True

优化:

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        return n > 0 and bin(n).count("1") == 1

方法二:O(1)

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        return n > 0 and n & (n - 1) == 0

方法三:O(logn)

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        if n == 0: return False
        while n % 2 == 0:
            n //= 2
        return n == 1

 

leetcode-231-2的幂

原文:https://www.cnblogs.com/oldby/p/11625041.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!