문제 풀이

[백준] 11021번: A+B-7 - JAVA (자바)

auyeol 2023. 1. 25. 10:22
728x90

 

 

문제

https://www.acmicpc.net/problem/11021

 

11021번: A+B - 7

각 테스트 케이스마다 "Case #x: "를 출력한 다음, A+B를 출력한다. 테스트 케이스 번호는 1부터 시작한다.

www.acmicpc.net

 

A+B할 식의 개수(n개)를 정한 뒤, 두 정수 A와 B를 입력, A+B를 한 결과를 출력하는 문제다.

 

이전에 푼 문제에서 출력결과만 바꾸면 맞는 문제라서 크게 어려움은 없었다.

 

 

-----------------------------------------------------------------------------------------------------------------------------------------------------------------

 

풀이

 

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int i;
		int n = sc.nextInt();
		int a = 0;
		int b = 0;
		int array[] = new int[n];
		
		for(i = 0;i < n;i++) 
		{
			a = sc.nextInt();
			b =sc.nextInt();
			array[i] = a+b;
		}
		
		for(i = 0;i < n;i++) 
		{
			System.out.print("Case #");
			System.out.println((i+1)+": "+array[i]);
		}
		
	}

}

 

 

 

15552번에서 시간초과로 못풀었던 적이 있어 BufferedReader와 BufferedWriter도 써봤다.

 

 

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader; 
import java.io.OutputStreamWriter;


public class Main {
	public static void main(String[] args) throws IOException{ 
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		int n = Integer.parseInt(br.readLine());
		
		for(int i = 0; i<n;i++) {
			String str = br.readLine();
			int a = Integer.parseInt(str.split(" ")[0]);
			int b = Integer.parseInt(str.split(" ")[1]);
			bw.write("Case #"+(i+1)+": "+(a+b)+"\n"); 
		}
		br.close();
		bw.flush(); 
		bw.close();
	}
}

 

 

버퍼를 사용했을 때가 메모리, 시간 모두 스캐너보다 뛰어났다.

728x90