我想從標準輸入中讀取一些非常大的數字並將它們添加在一起。如何將字符串轉換爲BigInteger?
然而,添加到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)
?