题目简介
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的个数
自己的解法
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
int s = 2;
int y;
while(s != 0){
s = n/2;
y = n%2;
if(y == 1)
count++;
n = s;
}
return count;
}
}
you need to treat n as an unsigned value
坑爹呀,这道题并不是考察我们10进制转2进制,所以题目中给的是int而不是unsigned int,题目中任然让我们把它当做unsigned int.所以我的提交没有通过卡到了2147483648这个测试用例上。
Hot解法
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int ones = 0;
while(n!=0) {
ones = ones + (n & 1);
n = n>>>1;
}
return ones;
}
}
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int ones = 0;
while(n!=0) {
n = n & (n - 1);
ones++;
}
return ones;
}
}
n = 10100(二进制),则(n-1) = 10011 ==》n&(n-1) = 10000
可以看到原本最低位为1的那位变为0。
可以看到原本最低位为1的那位变为0。
在我们的题目中只要一直进行这一步操作,进行一次加一,知道这个数为0,也就计算出了当前数字二进制中1的个数.
参考http://blog.youkuaiyun.com/zheng0518/article/details/8882394(有关n = n & (n -1)的用法大家可以去看一下)