[Leetcode231] 2的幂

给定一个整数,编写一个函数来判断它是否是 2 的幂次方。

这道题最好的方法就是用二进制。如果n是2的幂,那么n的二进制只有一个1,同时也表示它是刚刚进位,意味着它和(n-1)的二进制正好互补。所以可以有两个思路。

python:

class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <=0 :
            return False
        s = bin(n)#s = 'ob****'
        return s[2:].count('1') == 1

C++思路1: 

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n <= 0) return false;
        return bitset<32>(n).count() == 1;
    }
};

C++思路2: 

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n <= 0) return false;
        if(n & (n-1)) return false;
        else return true;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40501689/article/details/82966303