Java, comparing BigInteger values

前端 未结 3 1232
囚心锁ツ
囚心锁ツ 2021-02-05 05:25
BigInteger bigInteger = ...;


if(bigInteger.longValue() > 0) {  //original code
    //bigger than 0
}

//should I change to this?
if(bigInteger.compareTo(BigInteger.         


        
3条回答
  •  我在风中等你
    2021-02-05 05:42

    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.

    The second approach is better (see Bozhos answer for an optimization).

    Another alternative: BigInteger#signum returns 1 if the value is positive:

    if (bigInteger.signum() == 1) {
     // bigger than 0
    }
    

提交回复
热议问题