问题描述
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011
, so the function should return 3.
思路分析
给一个32位unsigned int,计算它的位中有多少个1。
现学现用,使用bitset计算。
代码
class Solution {
public:
int hammingWeight(uint32_t n) {
bitset<32> x(n);
int count = 0;
for (int i = 0; i < 32; i++){
if (x[i] != 0)
count++;
}
return count;
}
};
时间复杂度: O(1)
反思
使用bitset非常简单。