我试图从标准输入读取一些非常大的数字并将它们相加。
然而,要添加到BigInteger中,我需要使用 BigInteger.valueOf(long);
:
private BigInteger sum = BigInteger.valueOf(0);
private void sum(String newNumber) {
// BigInteger is immutable, reassign the variable:
sum = sum.add(BigInteger.valueOf(Long.parseLong(newNumber)));
}
那个方法很好用,但是由于 BigInteger.valueOf()
只接受 long
类型,所以我不能添加比 long
的最大值 (9223372036854775807) 更大的数字。
每次我尝试添加 9223372036854775808 或更多的数字时,都会得到 NumberFormatException 异常(这完全是可以预料的)。
是否有类似于 BigInteger.parseBigInteger(String)
的东西?