Programming/Algorithm

백준 알고리즘 2338번 긴자리 계산 JAVA

마실개 2022. 1. 23. 16:00
반응형

 

백준 알고리즘 2338번 긴자리 계산 JAVA 언어로 풀이 해보았다.

 

출처 백준 알고리즘

 

오류 발생

 

처음엔 단순하게 integer 타입으로 받아 처리하면 될 것이라 생각했지만

runtimeException 으로 오류가 발생했다.

 

그 이유를 잘 살펴보니 10진수로 1,000자리 까지 라는 조건이 있었다.

integer 타입의 범위가 다 담지 못하니 타입을 찾는 도중 BigInteger 라는 타입이 있었다.

 

 

import java.math.BigInteger;
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		
		BigInteger a = in.nextBigInteger();
		BigInteger b = in.nextBigInteger();
		
       		in.close();
        
		System.out.println(a.add(b));
		System.out.println(a.subtract(b));
		System.out.println(a.multiply(b));
		
	}

}

 

 

사용법

 

BigInteger 타입을 사용할땐 + - 와 같이 연산기호가 먹질 않는다.

더하기는 add()

빼기는 subtract()

곱하기는 multiply()

나누기는 mod()

나머지 구하기는 divide() 를 사용하면 된다.

 

어렵진 않았지만 이렇게 데이터 타입에 대해 또 한번 고민하게 되는 문제였다.

반응형