位运算,两种解法:
解法一:
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while ( n > 0 ) {
if ( n & 1 )
++count;
n >>= 1;
}
return count;
}
};
解法二:
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while ( n ) {
++count;
n = n & ( n - 1 );
}
return count;
}
};