How do I convert a String to a BigInteger?

微笑、不失礼 提交于 2019-11-26 12:45:16

问题


I\'m trying to read some really big numbers from standard input and add them together.

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)));
}

That works fine, but as the BigInteger.valueOf() only takes a long, I cannot add numbers greater than long\'s max value (9223372036854775807).

Whenever I try to add 9223372036854775808 or more, I get a NumberFormatException (which is completely expected).

Is there something like BigInteger.parseBigInteger(String)?


回答1:


Using the constructor

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

Javadoc




回答2:


According to the documentation:

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

It means that you can use a String to initialize a BigInteger object, as shown in the following snippet:

sum = sum.add(new BigInteger(newNumber));



回答3:


BigInteger has a constructor where you can pass string as an argument.

try below,

private void sum(String newNumber) {
    // BigInteger is immutable, reassign the variable:
    this.sum = this.sum.add(new BigInteger(newNumber));
}



回答4:


Instead of using valueOf(long) and parse(), you can directly use the BigInteger constructor that takes a string argument:

BigInteger numBig = new BigInteger("8599825996872482982482982252524684268426846846846846849848418418414141841841984219848941984218942894298421984286289228927948728929829");

That should give you the desired value.




回答5:


For a loop where you want to convert an array of strings to an array of bigIntegers do this:

String[] unsorted = new String[n]; //array of Strings
BigInteger[] series = new BigInteger[n]; //array of BigIntegers

for(int i=0; i<n; i++){
    series[i] = new BigInteger(unsorted[i]); //convert String to bigInteger
}


来源:https://stackoverflow.com/questions/15717240/how-do-i-convert-a-string-to-a-biginteger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!