如何将String转换为BigInteger? [英] How do I convert a String to a BigInteger?
问题描述
我正在尝试从标准输入读取一些非常大的数字并将它们加在一起。
I'm trying to read some really big numbers from standard input and add them together.
但是,要添加到BigInteger,我需要使用 BigInteger.valueOf(long);
:
However, to add to BigInteger, I need to use 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)。
That works fine, but as the BigInteger.valueOf()
only takes a long
, I cannot add numbers greater than long
's max value (9223372036854775807).
每当我尝试添加9223372036854775808或更多时,我会得到一个NumberFormatException(完全可以预料到)。
Whenever I try to add 9223372036854775808 or more, I get a NumberFormatException (which is completely expected).
是否有类似 BigInteger.parseBigInteger(String)
?
推荐答案
使用构造函数
BigInteger(String val)
BigInteger(String val)
翻译将BigInteger的十进制字符串表示形式转换为BigInteger。
Translates the decimal String representation of a BigInteger into a BigInteger.
这篇关于如何将String转换为BigInteger?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!