development

문자열을 BigInteger로 어떻게 변환합니까?

big-blog 2020. 12. 3. 08:06
반응형

문자열을 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)있습니까?


생성자 사용

BigInteger (문자열 발)

BigInteger의 10 진수 문자열 표현을 BigInteger로 변환합니다.

Javadoc


문서 에 따르면 :

BigInteger (문자열 발)

BigInteger의 10 진수 문자열 표현을 BigInteger로 변환합니다.

이는 다음 스 니펫에 표시된대로 String사용 하여 BigInteger객체 를 초기화 할 수 있음을 의미합니다 .

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

BigInteger에는 문자열을 인수로 전달할 수있는 생성자가 있습니다.

아래에서 시도해보십시오.

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

대신에 사용하는 valueOf(long)parse()직접 문자열 인수를 취하는 BigInteger의 생성자를 사용할 수 있습니다 :

BigInteger numBig = new BigInteger("8599825996872482982482982252524684268426846846846846849848418418414141841841984219848941984218942894298421984286289228927948728929829");

그것은 당신에게 원하는 가치를 줄 것입니다.


arrayof stringsof 로 변환하려는 루프의 경우 다음 arraybigIntegers수행하십시오.

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
}

참고 URL : https://stackoverflow.com/questions/15717240/how-do-i-convert-a-string-to-a-biginteger

반응형