思路:
这道题有很多种做法,最简单的就是循环遍历32位,还有一种高效的做法就是利用lowbit去做,lowbit返回值表示元素的二进制中最后一个1的数值,哪怕是负数,他也会计算所有位的,包括符号位。
代码:
class Solution {
public:
int low_bit(uint32_t n){
return n&(-n);
}
int hammingWeight(uint32_t n) {
int ans = 0;
if(n==0)return 0;
while(n){
n-=low_bit(n);
++ans;
}
return ans;
}
};