题目:
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.
即求出无符号32位整数的二进制数1的位数
最简单的思路既是:右移一位数与1做与运算,结果自加,直至右移32位结束
class Solution {
public:
int hammingWeight(uint32_t n) {
int result = 0, left = 0;
while(n != 0) {
left = n & 0x01;
result += left;
n >>= 1;
}
return result;
}
};
另一种奇妙的解法:参考此博文
n = 0x110100 n-1 = 0x110011 n&(n - 1) = 0x110000
n = 0x110000 n-1 = 0x101111 n&(n - 1) = 0x100000
n = 0x100000 n-1 = 0x011111 n&(n - 1) = 0x0
看到这里已经得到了一种新的解法,n中本来有3个1,按照此种思路只需要循环3此即可求出最终结果
class Solution {
public:
int hammingWeight(uint32_t n) {
int result = 0;
while(n != 0) {
n &= (n - 1);
result++;
}
return result;
}
};