题目:
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.
代码1:
class Solution {
public:
int hammingWeight(uint32_t n) {
int res;
while(n>0) {
res += n % 2;
n /2 = 2;
}
return res;
}
};
用了除法,速度较慢
class Solution {
public:
int hammingWeight(uint32_t n) {
int res;
while(n>0) {
res += (n & 0x01);
n = n>>1;
}
return res;
}
};
使用移位,速度较快