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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
方法一:
将n与n-1进行与运算。则可消除掉最右面的一个1,其余不变。
所以,需要计算几次后,得到n=0,则n中有几个1.
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++;
}
return count;
}
思路是很好的。计算次数真的很小
但是有问题。会报错。
2147483648, 转化为二进制位 1000,0000,0000,0000,0000,0000,0000,0000(总共32位,后11位均为0)
所以应该输出1. 但是这种方法输出为0.
而int型,最大为2147483647.
至于为什么输出0,我也不知道。。。谁能告诉我?
方法二:
这个方法的思路是:将一个1,放在每一位上试一下,如果和n求与之后,结果为0,那么这一位上的bite肯定是0,否则是1.
所以数一下不为0的个数即可。
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
for(int i = 0; i < 32; i++){
if (getBit(n,i) == true){
count++;
}
}
return count;
}
public boolean getBit(int n, int i){
return (n & (1 << i)) != 0;
}
}