문자열을 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로 변환합니다.
문서 에 따르면 :
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");
그것은 당신에게 원하는 가치를 줄 것입니다.
array
of strings
를 of 로 변환하려는 루프의 경우 다음 array
을 bigIntegers
수행하십시오.
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
'development' 카테고리의 다른 글
Bash 배열에 요소가 있는지 확인 (0) | 2020.12.03 |
---|---|
스크립팅을 사용하여 stdout을 파일과 콘솔 모두로 리디렉션하는 방법은 무엇입니까? (0) | 2020.12.03 |
Swift 3 UnsafePointer ($ 0)는 더 이상 Xcode 8 베타 6에서 컴파일되지 않습니다. (0) | 2020.12.03 |
Visual Studio Build Framework에서 .NET Core 2.2를 선택할 수 없음 (0) | 2020.12.03 |
개체가 VBA에서 컬렉션의 구성원인지 확인 (0) | 2020.12.03 |