문자열을 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()
1개만 가져가면long
, 다음보다 큰 숫자를 추가할 수 없습니다.long
의 최대값(9223372036854775807)
9223372036854775808 이상을 추가하려고 하면 번호가 표시됩니다.Format Exception(완전 예상).
뭐 이런 거 있어요?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
의strings
에 대해서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
}
일반 텍스트(숫자뿐 아니라)를 BigInteger로 변환하려고 하면 예외가 발생합니다.새로운 BigInteger("숫자가 아닙니다")
이 경우 다음과 같이 할 수 있습니다.
public BigInteger stringToBigInteger(String string){
byte[] asciiCharacters = string.getBytes(StandardCharsets.US_ASCII);
StringBuilder asciiString = new StringBuilder();
for(byte asciiCharacter:asciiCharacters){
asciiString.append(Byte.toString(asciiCharacter));
}
BigInteger bigInteger = new BigInteger(asciiString.toString());
return bigInteger;
}
언급URL : https://stackoverflow.com/questions/15717240/how-do-i-convert-a-string-to-a-biginteger
'programing' 카테고리의 다른 글
Ubuntu 14.04에 PHP intl 확장을 설치하는 방법 (0) | 2022.11.23 |
---|---|
이클립스용 매크로 레코더 있어? (0) | 2022.11.23 |
MariaDB 명령이 동기화되지 않음 (0) | 2022.11.23 |
Windows에서 Ubuntu Linux 18.04 WSL: MariaDB 서비스 시작 실패 (0) | 2022.11.23 |
URL에 PHP가 포함된 특정 문자열이 있는지 확인합니다. (0) | 2022.11.23 |