返回信息流public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int c = 0;
if(n > 0)
while(! (n >= Math.pow(2,c) && n < Math.pow(2,c+1) ) )
c ++;
else
return 0;
int[] a = new int[c+1];
for(int i = 0; i < a.length; i++){
a[i] = n % 2;
n = n / 2;
}
int oneCount = 0;
for(int i = 0; i < a.length; i++)
if(a[i] == 1)
oneCount ++;
return oneCount;
}
}
但题目中要求把n当作unsigned值用。
然而传进来的值就是int型,怎么搞也不能改变它的范围啊……
我写的方法可以得到0~2^31-1的正确结果,然而到2^31 = 2147483648就错了
想请教各位是怎么实现的[ema1]
这是一条镜像帖。来源:北邮人论坛 / java / #50772同步于 2016/5/30
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
[问题]LeetCode 191题(easy)Number of 1 Bits 无法通过
z3278221
2016/5/30镜像同步15 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
count++;
n &= (n - 1);
}
return count;
}
【 在 z3278221 的大作中提到: 】
: public class Solution {
: // you need to treat n as an unsigned value
: public int hammingWeight(int n) {
: ...................
首先谢谢你,
还想问一下,为什么while的判定一定要写n!=0,我写n>0也会报超出范围
【 在 Lamperouge 的大作中提到: 】
: [code=java]
: public int hammingWeight(int n) {
: int count = 0;
: ...................
int hammingWeight(uint32_t n) {
int count=0;
while(n)
{
count += n%2;
n=n/2;
}
return count;
}