问题描述
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,那么自然先想到第一种,即一位一位向右位移,数出1的个数,伪代码如下:
while(0 != n)
{
left = n & 0x1;
re += left;
n = n >> 1;
}
但是此种方法较慢,对于0x1ffffff的判定需要循环32次才能计算出结果,超时。
故转换思路,举例:
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此即可求出最终结果,比第一种暴力枚举的解法要少很多次。最终实现代码如下,AC:
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int re = 0;
while(0 != n)
{
n = n&(n - 1);
++re;
}
return re;
}
}