题目 : 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位的整数,计算它的汉明重量。 先将它转化成二进制形式保存到vector中,再计算1的值,很简单
代码:
class Solution {
public:
int hammingWeight(uint32_t n) {
vector<int> ivec;
int count =
0;
while (n){
ivec.push_back(n %
2);
n /=
2;
}
for (
vector<int>::iterator ix = ivec.begin(); ix != ivec.end(); ++ix){
if (*ix ==
1){
++count;
}
}
return count;
}
};
转载请注明原文地址: https://ju.6miu.com/read-11676.html