Java,比较BigInteger值 [英] Java, comparing BigInteger values
问题描述
BigInteger bigInteger = ...;
if(bigInteger.longValue() > 0) { //original code
//bigger than 0
}
//should I change to this?
if(bigInteger.compareTo(BigInteger.valueOf(0)) == 1) {
//bigger than 0
}
我需要比较一些任意的BigInteger值。我想知道哪种方法是正确的。鉴于以上代码应该使用哪一个?原始代码在顶部..我正在考虑将其更改为第二种方法。
I need to compare some arbitary BigInteger values. I wonder which approach is correct. Given the above code which one should be used? The original code is on the top.. I am thinking to change it to the second approach.
推荐答案
第一种方法是错误的如果你想测试BigInteger是否有一个正值: longValue
只返回低位64位,这可能会恢复符号...因此,对于积极的BigInteger,测试可能会失败。
The first approach is wrong if you want to test if the BigInteger has a postive value: longValue
just returns the low-order 64 bit which may revert the sign... So the test could fail for a positive BigInteger.
第二种方法更好(参见 Bozhos回答进行优化。)
The second approach is better (see Bozhos answer for an optimization).
另一种选择: BigInteger #ignumum
如果值为正,则返回 1
:
Another alternative: BigInteger#signum
returns 1
if the value is positive:
if (bigInteger.signum() == 1) {
// bigger than 0
}
这篇关于Java,比较BigInteger值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!