Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as theHamming weight).
For example, the 32-bit integer ’11' has binary representation00000000000000000000000000001011
, so the function should return 3.
这道题是找出一个二进制非负整数中‘1’的个数,题目难度为easy。
这道题比较简单,通过移位操作依次查看最低位是否为1进行统计,具体代码:
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt = 0;
while(n) {
cnt += (n&0x1);
n >>= 1;
}
return cnt;
}
};
另外看到有人用一种比较巧妙的方法跳过了‘0’位的循环,具体见代码:
class Solution {
public:
int hammingWeight(uint32_t n) {
int cnt = 0;
while(n) {
cnt ++;
n &= (n-1);
}
return cnt;
}
};
不过,运行时间比前一种方法要长。。囧。。