Twi*_*one 65 java string 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)));
}
Run Code Online (Sandbox Code Playgroud)
这工作正常,但由于BigInteger.valueOf()唯一需要a long,我不能添加大于long最大值的数字(9223372036854775807).
每当我尝试添加9223372036854775808或更多时,我都会得到一个NumberFormatException(完全可以预料到).
有类似的东西BigInteger.parseBigInteger(String)吗?
Vit*_*ile 21
根据文件:
BigInteger(String val)
将BigInteger的十进制字符串表示形式转换为BigInteger.
这意味着您可以使用a String来初始化BigInteger对象,如以下代码段所示:
sum = sum.add(new BigInteger(newNumber));
Run Code Online (Sandbox Code Playgroud)
BigInteger具有构造函数,您可以在其中传递字符串作为参数.
试试下面,
private void sum(String newNumber) {
// BigInteger is immutable, reassign the variable:
this.sum = this.sum.add(new BigInteger(newNumber));
}
Run Code Online (Sandbox Code Playgroud)
小智 7
您可以直接使用带有字符串参数的BigInteger构造函数,而不是使用valueOf(long)和parse():
BigInteger numBig = new BigInteger("8599825996872482982482982252524684268426846846846846849848418418414141841841984219848941984218942894298421984286289228927948728929829");
Run Code Online (Sandbox Code Playgroud)
这应该给你想要的价值.
| 归档时间: |
|
| 查看次数: |
170700 次 |
| 最近记录: |