题目:
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.
思路:
也是送分题目。。。
代码:
class Solution {
public:
int hammingWeight(uint32_t n) {
int hamming_weight = 0;
while (n > 0) {
hamming_weight += (n % 2);
n /= 2;
}
return hamming_weight;
}
};
计算整数二进制位中1的数量
本文介绍了一个简单的方法来计算一个无符号整数的二进制表示中‘1’的数量(即汉明重量)。通过一个C++实现的例子展示了如何遍历整数的每一位并累加‘1’的个数。
380

被折叠的 条评论
为什么被折叠?



