Skip to content

Latest commit

 

History

History
65 lines (45 loc) · 1.51 KB

231-power-of-two.md

File metadata and controls

65 lines (45 loc) · 1.51 KB

231. Power of Two - 2的幂

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

示例 1:

输入: 1
输出: true
解释: 20 = 1

示例 2:

输入: 16
输出: true
解释: 24 = 16

示例 3:

输入: 218
输出: false

题目标签:Bit Manipulation / Math

题目链接:LeetCode / LeetCode中国

题解

利用位运算来判断是否为2的幂。2的幂的二进制特点是:最高位为1,其余全为0;而2的幂-1的二进制特点是:所有位都为1。因此,进行按位与,结果是0。

Language Runtime Memory
cpp 4 ms N/A
class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n > 0)
            return !(n & (n-1));
        else
            return false;
    }
};
Language Runtime Memory
python3 56 ms N/A
class Solution:
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        return not (n & (n-1)) if n > 0 else False