문제
두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
입력
첫째 줄에 A와 B가 주어진다. (0 < A,B < 10^10000)
출력
첫째 줄에 A+B를 출력한다.
| 예제입력 | 예제출력 |
| 9223372036854775807 9223372036854775808 | 18446744073709551615 |
⭕ 풀이
import java.io.*;
import java.util.*;
import java.math.*;
public class Main{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
BigInteger A = new BigInteger(st.nextToken());
BigInteger B = new BigInteger(st.nextToken());
System.out.print(A.add(B));
}
}
✅ BinInteger
자바에서 정수 int 타입의 범위는 -2,147,483,648 ~ 2,147,483,647
정수 long타입의 범위는 -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807
예제의 수들은 long타입의 최대범위이므로 long타입으로는 받을 수 없다
그래서 math패키지에 있는 BigINteger클래스를 활용해야한다.
BigInteger는 생성하며 숫자로이루어진 문자열을 받는다.
BigInteger A = new BigInteger("9223372036854775807");
BigInteger B = new BigInteger("9223372036854775808");
와 마찬가지이며 BigInteger는 문자열이므로 평소에 사용하던 사칙연산 기호를 사용해 연산할 수 없다.
때문에 BigInteger클래스에는 각각의 메서드가 존재하는데 연산관련 메서드만 보자.
BinInteger를 더하는 BigInteger.add(BigInteger타입의 값);
BinInteger를 빼는 BigInteger.subtract(BigInteger타입의 값);
BinInteger를 곱하는 BigInteger.multiply(BigInteger타입의 값);
BinInteger를 나누는 BigInteger.divide(BigInteger타입의 값);
BinInteger를 나머지 BigInteger.remainder(BigInteger타입의 값);
-출처
'Algorithm > Baekjoon(Java)' 카테고리의 다른 글
| [백준/JAVA] 2581 : 소수 찾기 ( 기본 수학 2 ) (0) | 2022.08.08 |
|---|---|
| [백준/JAVA] 1978 : 소수 찾기 ( 기본 수학 2 ) (0) | 2022.08.07 |
| [백준/JAVA] 2839 : 설탕 배달 ( 기본 수학 1 ) (0) | 2022.08.05 |
| [백준/JAVA] 2775 : 부녀회장이 될테야 ( 기본 수학 1 ) (0) | 2022.08.04 |
| [백준/JAVA] 10250 : ACM호텔 ( 기본 수학 1 ) (0) | 2022.08.03 |