如何将String转换为BigInteger?

编程入门 行业动态 更新时间:2024-10-13 22:24:28
本文介绍了如何将String转换为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.

Javadoc

更多推荐

如何将String转换为BigInteger?

本文发布于:2023-06-08 21:31:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/589417.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何将   String   BigInteger

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!