[191. Number of 1 Bits])(https://leetcode-cn.com/problems/number-of-1-bits/)
4ms 85.72% 思路一:逐位取出n,然后计数。
8ms 54.89% 思路二:使用bitset库
思路一
class Solution {
public:
int hammingWeight(uint32_t n) {
int ans=0,k=32;
while(k-->0){
if(n&1)ans++;
n=n>>1;
}
return ans;
}
};
思路二
class Solution {
public:
int hammingWeight(uint32_t n) {
bitset<32> b(n);
return b.count();
}
};