题很简单,原题如下:
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>0)
{
n=n&(n-1);
ans++;
}
return ans;
}
};
本文介绍了一种计算32位无符号整数二进制表示中1的个数的方法。通过使用按位与操作,每次迭代减少最高位1的数量,直至整数变为0。此方法高效地实现了汉明重量(Hamming Weight)的计算。
542

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



