class Solution {
public:
//法一:移位运算 运算32次 //时间消耗大4ms,击败40.59%; 内存5.9MB,击败88.78%
int hammingWeight(uint32_t n) {
int count = 0;
while(n)
{
if(n & 1) count++;
n = n >> 1;//必须是n=n>>1;否则n一直是原来的数
}
return count;
}
//上述运算存在风险,如果输入是有符号的负数,移位最终导致所有位变为1,陷入死循环
//改进方法一:不移动n,移动flag
// int hammingWeight(int32_t n) {
// int count = 0;
// uint32_t flag = 1;
// while(flag)
// {
// if(n & flag) count++;
// flag = flag << 1;//必须是n=n>>1;否则n一直是原来的数
// }
// return count;
// }
//法二:x&(x-1)去掉最后的1 运算16次 //时间消耗为0ms
// int hammingWeight(uint32_t n) {
// int count = 0;
// while(n)
// {
// n = n & (n - 1);
// count++;
// }
// return count;
// }
};