版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50506429
翻译
写一个函数获取一个无符号整型数,并且返回它的“1”比特的数目(也被叫做Hamming weight)。
例如,一个32位整型数“11”,转换成二进制是00000000000000000000000000001011,所以这个函数应该返回3。
原文
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 count = 0;
while (n) {
++count;
n = (n - 1) & n;
}
return count;
}
};