BigInteger
Java에는 수많은 자료형이 존재합니다.
아래 표와 같이 숫자들을 여러가지 방법으로 표현할 수 있지만, 이중 가장 넓은 범위를 갖는것이 BigInteger입니다.
char | 16비트 유니코드(Unicode) 문자 데이터 | 16 | ‘\u0000’ ~ ‘\uFFFF’ |
boolean | 참/거짓 값 | 8 | true 또는 false |
byte | 부호를 가진 8비트 정수 | 8 | -128 ~ +127 |
short | 부호를 가진 16비트 정수 | 16 | -32,768 ~ +32,767 |
int | 부호를 가진 32비트 정수 | 32 | -2,147,483,638~+2,147,483,647 |
long | 부호를 가진 64비트 정수 | 64 | -9223372036854775808~+9223372036854775807 |
float | 부호를 가진 32비트 부동 소수점 | 32 | -3.402932347e+38~+3.40292347e+38 |
double | 부호를 가진 64비트 부동 소수점 | 64 | -179769313486231570e+308~1.79769313486231570e+08 |
그럼 어떻게 사용할까?
생성
BigInteger 같은경우 생성자에 "String" 타입의 매개변수를 넣어준다
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BigInteger example = new BigInteger("0");
}
왜?
BigInteger의 인터페이스 구현체를 봐보자.
* 빅 정수의 10진수 문자열 표현을 다음과 같이 변환합니다.
* 빅 정수. 문자열 표현은 선택적 빼기로 구성됩니다.
* 기호 뒤에 하나 이상의 소수 자릿수가 표시됩니다. 그
* 문자 대 숫자 매핑은 {@codeCharacter.digit}에서 제공합니다.
* 문자열에는 관련 없는 문자(공백, 다음)를 사용할 수 없습니다.
/**
* Translates the decimal String representation of a BigInteger into a
* BigInteger. The String representation consists of an optional minus
* sign followed by a sequence of one or more decimal digits. The
* character-to-digit mapping is provided by {@code Character.digit}.
* The String may not contain any extraneous characters (whitespace, for
* example).
*
* @param val decimal String representation of BigInteger.
* @throws NumberFormatException {@code val} is not a valid representation
* of a BigInteger.
* @see Character#digit
*/
public BigInteger(String val) {
this(val, 10);
}
그렇다면 String형인데 어떻게 산술연산이 가능할까?
BigInteger 같은 경우, 기본적인 Integer형 산술연산이 불가능하다
ex) +, - , / , %
BigInteger 산술연산
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BigInteger a = new BigInteger("10");
BigInteger b = new BigInteger("30");
// a+b
System.out.println(a.add(b));
// a-b
System.out.println(a.subtract(b));
// a*b
System.out.println(a.multiply(b));
// a/b
System.out.println(a.divide(b));
// a%b
System.out.println(a.remainder(b));
}
}
참고자료
'language > Java' 카테고리의 다른 글
[Java] String.valueOf vs toString (0) | 2022.06.09 |
---|