解法:位与, 如果n是2的幂,则n的二进制的最高位为1其余位为0,n-1的二进制最高位为0,其余位为1。
class Solution {
private:
static constexpr int BIG = 1 << 30;
public:
bool isPowerOfTwo(int n) {
return n > 0 && (n & (n-1));
};
class Solution {
private:
static constexpr int BIG = 1 << 30;
public:
bool isPowerOfTwo(int n) {
int ans = 0;
bool flag = false;
if(n > 0){
ans = BIG % n;
if(ans == 0)
return true;
}
else{
return false;
}
return flag;
}
};
191.位1的个数
解法:左移<<
class Solution {
public:
int hammingWeight(uint32_t n) {
int ret = 0;
for(int i = 0; i < 32; i++){
if(n & (1 << i)){ //当n的第i位为1时,条件成立
ret++;
}
}
return ret;
}
};



