백준 10757

hong030·2023년 1월 25일
0
  • solved.ac 기준 브론즈 5 단계 문제

풀이)
byte: 8비트 저장공간을 가지고 있으며 부호있는 정수를 담을 수 있어 범위는 -2^7~ +2^7
short: 16비트 저장공간을 가지고 있으며 부호있는 정수를 담을 수 있어 범위는 -2^15~ +2^15
int: 32비트 저장공간을 가지고 있으며 부호있는 정수를 담을 수 있어 범위는 -2^31~ +2^31
long: 64비트 저장공간을 가지고 있으며 부호있는 정수를 담을 수 있어 범위는 -2^63~ +2^63

즉, 문제에서 요구하는 10^10000승의 정수를 담을 수 있는 저장공간은 없다.

때문에 큰 정수를 담을 수 있는 BigInteger 클래스를 활용하여 문제를 풀자. BigInteger은 문자열 형태로 이루어져 숫자를 무한으로 담을 수 있다. 단, 문자열 클래스이기 때문에 단순 사칙연산은 안되고 내부 메소드를 사용해야 한다.

내 코드)

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

public class Main {
	public static void main(String[] args){
		Scanner s = new Scanner(System.in);
		BigInteger a = new BigInteger(s.next());
		BigInteger b = new BigInteger(s.next());
		
		System.out.println(a.add(b));
	}
}

내 코드 2)
Scanner 을 사용했을 때 시간이 좀 걸려서 BufferedReader 도 사용해봤다.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.StringTokenizer;

public class Main {
	public static void main(String[] args) throws IOException {
		
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		
		StringTokenizer st = new StringTokenizer(bf.readLine());
		
		BigInteger b1 = new BigInteger(st.nextToken());
		BigInteger b2 = new BigInteger(st.nextToken());
		
		System.out.println(b1.add(b2));
		bf.close();
	}
}

시간 차이가 조금 있다. BufferedReader에도 익숙해져야겠다.

profile
자바 주력, 프론트 공부 중인 초보 개발자. / https://github.com/hongjaewonP

0개의 댓글