题目
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,都是把最右边的1变成0.如果它的右边还有0,的话,所有的0变成1,而它左边所有位都保持不变。
2,接下来我们把一个整数和它减去1的结果做位运算,相当于把它最右边的1变成0,。还是以前面的1100为例,它减去1的结果是1011。我们再把1100和1011做位与运算,得到的结果是1000。我们把1100最右边的1变成了0,结果刚好就是1000。
3,我们把上面的分析结果总结起来就是:把一个整数减去1,再和原整数做与运算,会把该整数最右边的一个1变成0。那么一个整数的二进制表示中有多少个1,就可以进行多少次这样的操作。
4,基于这种思路,我们可以写出新的代码(如下所示)。
解
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n != 0){
n = n & (n-1);
count++;
}//while
return count;
}
}
参考链接
参考链接1:
http://blog.163.com/kevinlee_2010/blog/static/169820820201541005951696/