题目:
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’的数量(也被称为汉明权重)。
例如,一个32位整数‘11’的二进制表示是00000000000000000000000000001011,所以函数返回3。
分析:
这道题目的考察点在于对无符号数的理解上。我们知道计算机中负数是采用补码进行表示的,例如存储为fffffffe的数,如果是当做无符号数,则是4294967294,如果是当做有符号数,则是-2。而Java中实际上没有无符号数的概念的,整数都是带符号位的。所以4294967294这个无符号数是会当做-2的,所以我们要解决的就是如何将-2(fffffffe)转换为4294967294。首先,要想存储4294967294,则必须使用long了,int表示不了。如果我们将-2直接转为long会变成fffffffffffffffe,这个时候我们需要通过位运算把前面的部分清零,也就是通过“与运算”来实现。
代码:
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
long nlong=n&0xFFFFFFFFL;
int sum=0;
while(nlong>0){
if(nlong%2==1){
sum++;
}
nlong/=2;
}
return sum;
}
}