https://www.acmicpc.net/problem/11382
Question
꼬마 정민이는 이제 A + B 정도는 쉽게 계산할 수 있다. 이제 A + B + C를 계산할 차례이다!
Input
첫 번째 줄에 A, B, C (1 ≤ A, B, C ≤ 10^12)이 공백을 사이에 두고 주어진다.
Output
A+B+C의 값을 출력한다.
Example
input
77 77 7777
output
7931
Answer
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
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(), " ");
long res = 0;
while(st.hasMoreTokens()) res += Long.parseLong(st.nextToken());
System.out.println(res);
br.close();
}
}
Answer - Code Explanation
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferReader 클래스는 데이터를 버퍼에 저장해두었다가 한번에 입력하는 방식으로 동작한다.
즉, 데이터를 하나씩 입력하는 것이 아니라 한번에 입력하므로 속도가 빠르다.
(입출력이 많은 코드나 데이터 양이 많은 경우에 지향하는 방식이다.)
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
StringTokenizer 클래스로 br.readLine()으로 읽어온 문자열을 " " 공백 기준으로 분리한다.
long res = 0;
결과를 int타입이 아닌 long타입을 한 이유는 문제의 입력 기준 1 ≤ A, B, C ≤ 10^12 에서 알 수 있다.
정수형 타입 | 메모리 크기 | 데이터 표현 범위 |
byte | 1 byte | -128 ~ 127 |
short | 2 byte | -215 ~ (215 - 1) |
-32,768 ~ 32,767 | ||
int | 4 byte | -231 ~ (231 - 1) |
-2,147,483,648 ~ 2,147,483,647 | ||
long | 8 byte | -263 ~ (264 - 1) |
-9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807 |
즉, 위 표와 같이 10의 12제곱은 int 형의 최대 데이터 표현 범위를 벗어났기 때문에 long 형을 사용해야 한다.
while(st.hasMoreTokens()) res += Long.parseLong(st.nextToken());
while(st.hasMoreTokens())로 토큰 값이 없을 때까지 조건 아래 식을 반복한다.
Long.parseLong(st.nextToken())으로 받은 문자 토큰을 Long 으로 형변환한다.
br.close();
Java에서는 GC를 통해서 Java 내의 객체 및 리소스들이 자동으로 정리되기 때문에 close()를 하지 않아도 큰 문제가 발생하지 않는다.
하지만 GC가 자동으로 모두 완료될 때까지 BufferedReader에 할당된 리소스들이 그대로 유지되고 있다.
따라서 최적화면에서 사용을 다한 BufferedReader 들은 close()를 선언하여 스트림을 닫아주는 것이 좋다.
Reference
https://fall-in-dream.tistory.com/35