python3 leetcode判断一个数是不是2的幂次方

当拿到这道题的时候我想的是进行
code:

import math
n=int(input('请输入一个正整数:'))
if math.log(n,2)==int:
    return True
else:
    return False

但是在leetcode这样运行时错误的,所以
代码修改如下:

class Solution:
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n==0:
            return False
        elif (n&(n-1)==0):
            return True
        else:
            return False

运行结果是正确的
其实这道题的思想就是利用了2^x的结果和二进制数之间的一个规律
n&(n-1)==0那么就可以判断n就是2的幂次方,但是可能还有0,这个需要单独判断了,除了这两种情况,其余的都可以归为一类,所以,代码如上所示。

猜你喜欢

转载自blog.csdn.net/lc574260570/article/details/81941705