Bit Manipulation - Power of Two

来源:互联网 发布:工业网络交换机 编辑:程序博客网 时间:2024/05/20 14:20

https://leetcode.com/problems/power-of-two/
Difficulty: Easy

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

2的幂次方,在二进制中,首位为1,其余位为零,只需要消去一个1之后判断其是否为零即可。另外需要注意的是,2的幂次方必为正整数

// Runtime: 8 msclass Solution {public:    bool isPowerOfTwo(int n) {        return n > 0 && !(n & (n - 1));    }};
0 0