您的位置:首页 > 其它

Number of 1 Bits

2015-03-12 07:40 99 查看
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.

思路有两种:

第一种:

将n二进制化,在二进制化的过程中统计1的个数

java中没有无符号整数的表示,所以不是很容易,int 的范围是-2147483648 ~ 2147483647

第二种:

利用按位与,统计1的个数
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
int tmp = 1;
int i = 0 ;
while(i < 32){
if((n & tmp) != 0 ){
count ++;
}
tmp = tmp << 1;
i++;
}
return count;
}
}
注意:& 的优先级低于 != ,所以n&tmp要加括号
Runtime: 220
ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: