BigInteger
- int, long과 달리 숫자를 문자열 형태로 처리해 담을 수 있는 숫자의 범위가 무한함
- 숫자가 기존 정수형 데이터 타입이 수용 가능한 범위를 넘어설 경우 사용
데이터 타입 | 크기 | 범위 |
int | 4 byte | -2³¹ ~ (2³¹-1) -2,147,483,648 ~ 2,147,483,647 |
long | 8 byte | -2⁶³ ~ (2⁶³-1) -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807 |
보통 입력되는 숫자가 위 범위를 벗어나는 경우는 잘 없으나 알고리즘 테스트 등에서 간혹 아주 큰 수를 입력받는 경우가 있다. 그때 사용한다.
선언
import java.math.BigInteger;
BigInteger bigInt = new BigInteger("1000");
//16진수 생성
BigInteger bigIntRadix = new BigInteger("1000", 16);
기본적으로 BigInteger를 초기화 할 땐 문자열을 인자로 넘겨준다.
연산
BigInteger는 문자열이기 때문에 인스턴스의 사칙연산을 위해선 클래스 내부 메소드를 사용해야 한다.
덧셈 | add() |
뺄셈 | subtract() |
곱셈 | multiply() |
나눗셈 | divide() |
BigInteger bigInt = new BigInteger("1000");
// 덧셈
System.out.println(bigInt.add(BigInteger.ONE)); //1001
// 뺄셈
System.out.println(bigInt.subtract(BigInteger.TWO)); //998
// 곱셈
System.out.println(bigInt.multiply(BigInteger.ZERO)); //0
// 나눗셈
System.out.println(bigInt.divide(BigInteger.TEN)); //100
📝관련 문제
https://www.acmicpc.net/problem/10757
'Java' 카테고리의 다른 글
[자바/오류] incompatible types: char cannot be converted to string (0) | 2024.07.04 |
---|---|
JDK 버전 변경 + IntelliJ 환경 설정 (0) | 2023.10.23 |
댓글