class Solution {
public:
int hammingWeight(uint32_t n) {
return (__builtin_popcount(n));
}
};
- Each time of "n &= n - 1", we delete one '1' from n.
int hammingWeight(uint32_t n){
int res = 0;
while(n){
n &= n - 1;
++ res;
}
return res;
}