Number of 1 Bits
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 ans = 0;
while (n) {
if (n & 1) ans++;
n >>= 1;
}
return ans;
}
};
本文介绍了一个计算无符号整数二进制表示中'1'位数量的函数实现。通过遍历整数的每一位并累加值为1的位数来计算Hamming Weight。示例展示了如何将该方法应用于具体的32位整数。
514

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



