[leetcode] Number of 1 Bits

1.先上题:

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.

2.一眼看到这个题感觉好简单,AC率才30%+,心里沾沾自喜。。 岂料,提交之后竟然WA了!!!!  测试用例中有个数据是2147483648,这是超出了JAVA int型范围的,不明白测试数据为什么会有这个?  这到底是why? (现在觉得可能就是下面这个无符号的问题 ,假如存在无符号,范围应该是0~2^32-1 )

    百度之后才知道原来 JAVA没有无符号类型 ,然后题的代码提示说 要把n 当做无符号数处理,所以只能位运算了!

3. 在JAVA中对于一个整型变量,其默认类型是int型,范围是-2^31~2^31-1 (-2147483648~2147483647) .

 AC代码:

public int hammingWeight(int n){

int record=0;
while(n!=0) {
record++;
n&=n-1;
}
//System.out.println(record);
return record;
}

在网上查一下都是推荐这种算法,但是不知道AC之后看到有很多100ms之内的算法,不知道大牛们是怎么实现的! 

 

posted @ 2015-05-06 17:44  summer323  阅读(137)  评论(0编辑  收藏  举报