您的位置:首页 > 其它

[LeetCode]: 191:Number of 1 Bits

2015-09-12 16:39 435 查看
题目:

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.

分析:

直接用"除二取余"的方法来获取二进制的值

代码如下:(C#)

public class Solution {
public int HammingWeight(uint n) {
int intResult = 0;
uint intTemp = n;

if(n<=1){
return (int)n;
}

while(intTemp > 0){
if(intTemp%2 ==1){
intResult++;
}
intTemp = intTemp/2;
}

return intResult;
}
}


同样的思路用Java提交会报错,主要原因如下:

- 输入值n可能为负数(但应视其为无符号整数,但Java中实际上是没有无符号整数的)

所以采用:无符号右移操作,可以忽略符号位。

代码如下(Java):

public class Solution {
public int hammingWeight(int n) {
int ans = 0;
while (n != 0) {
ans += n & 1;
n >>>= 1;
}
return ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: