Given an integer, write a function to determine if it is a power of two.
给一个整数,判断是否是2的幂。
2的幂的2进制数只有最高位为1,减1之后全为1。所以2的幂n&(n-1)==0.
代码如下:
class Solution {
public:
bool isPowerOfTwo(int n) {
return n>0 && ((n&(n-1))==0);
}
};
Given an integer, write a function to determine if it is a power of two.
给一个整数,判断是否是2的幂。
2的幂的2进制数只有最高位为1,减1之后全为1。所以2的幂n&(n-1)==0.
代码如下:
class Solution {
public:
bool isPowerOfTwo(int n) {
return n>0 && ((n&(n-1))==0);
}
};