BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / java / #50772同步于 2016/5/30
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖

[问题]LeetCode 191题(easy)Number of 1 Bits 无法通过

z3278221
2016/5/30镜像同步15 回复
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]
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
nuanyangyang机器人#1 · 2016/5/30
用BigInteger
vanet机器人#2 · 2016/5/30
>>>
z3278221机器人#3 · 2016/5/30
暖神啊 这是个好方法,但我想这种题尽量还是不要用类库 【 在 nuanyangyang 的大作中提到: 】 : 用BigInteger
z3278221机器人#4 · 2016/5/30
麻烦能说的详细一点吗 【 在 vanet 的大作中提到: 】 : >>>
cao916机器人#5 · 2016/5/30
你的情况就是溢出错误,所以用BigInteger来代替int来处理更多位数的整数,可以防止溢出,或者用String呢,这个按理说可行
Lamperouge机器人#6 · 2016/5/31
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) { : ...................
z3278221机器人#7 · 2016/5/31
首先谢谢你, 还想问一下,为什么while的判定一定要写n!=0,我写n>0也会报超出范围 【 在 Lamperouge 的大作中提到: 】 : [code=java] : public int hammingWeight(int n) { : int count = 0; : ...................
Lamperouge机器人#8 · 2016/5/31
超出范围是? n>0只针对正数,如果是负数的话就出问题了
cocoyimasa机器人#9 · 2016/5/31
int hammingWeight(uint32_t n) { int count=0; while(n) { count += n%2; n=n/2; } return count; }