CS/Baekjoon

[Algorithm] 백준 단계별로 풀어보기 - 단계 3

칸타탓 2019. 3. 30. 16:47

BaekJoon Oline Judge - Step 3

 

반복문 기초!

package algorithm.Beakjoon;

import java.util.Scanner;

public class BeakjoonStep3 {
	public static void main(String[] args) {
		//2741. 자연수 N이 주어졌을 때, 1부터 N까지 한 줄에 하나씩 출력
		/* Scanner scan = new Scanner(System.in);
		int N = scan.nextInt();
		
		for(int i=1; i<=N; i++) {
			System.out.println(i);
		} */
		
		//2742. 기찍 N
		/* Scanner scan = new Scanner(System.in);
		int N = scan.nextInt();
		
		for(int i=N; i>=1; i--) {
			System.out.println(i);
		} */
		
		//2739. 구구단
		/* Scanner scan = new Scanner(System.in);
		int N = scan.nextInt();
		
		for(int i=1; i<=9; i++) {
			System.out.println(N + " * " + i + " = " + N*i);
		} */
		
		//별 찍기 - 1
		/* Scanner scan = new Scanner(System.in);
		int N = scan.nextInt();
		
		for(int i=0; i<N; i++) {
			for(int j=0; j<=i; j++) {
				System.out.print("*");
			}
			System.out.println();
		} */
		//별 찍기 - 2
		/* Scanner scan = new Scanner(System.in);
		int N = scan.nextInt();
		
		for(int i=1; i<=N; i++) {
			for(int k=N-i; k>0; k--) {
				System.out.print(" ");
			}
			for(int j=1; j<=i; j++) {
				System.out.print("*");
			}
			System.out.println();
		} */
		//별 찍기 - 3
		/* Scanner scan = new Scanner(System.in);
		int N = scan.nextInt();

		for (int i = N; i > 0; i--) {
			for (int j = i; j > 0; j--) {
				System.out.print("*");
			}
			System.out.println();
		} */
		//별 찍기 - 4
		/* Scanner scan = new Scanner(System.in);
		int N = scan.nextInt();
		
		for(int i=N; i>=1; i--) {
			for(int k=0; k<N-i; k++) {
				System.out.print(" ");
			}
			for(int j=i; j>=1; j--) {
				System.out.print("*");
			}
			System.out.println();
		} */		
	} 
}

 

1914. 2007년

배열에 날짜와 요일을 저장해두고, 1월 1일부터 입력한 날짜까지의 총 날짜의 합을 구한 후 7로 나누어 요일을 구한다.

7로 나눈 나머지값이 요일이 되는 것!

//2007년
Scanner scan = new Scanner(System.in);
int x = scan.nextInt();
int y = scan.nextInt();
int totalDate = 0;
		
int[] month = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
String[] week = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};
		
//총 날짜
for(int i=0; i<x; i++) {
	totalDate = totalDate + month[i];
}
totalDate = totalDate + y;
//요일
int resIndex = totalDate % 7;
System.out.println(week[resIndex]);

 

11720. 숫자의 합

정수로 입력받으면 각자리 수를 더할 수 없기 때문에 문자열로 입력받은 다음 split을 통해 잘라 배열에 넣어준다.

그 배열을 반복문 돌려 숫자를 더해줘야한다.

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		//N개의 숫자가 공백 없이 쓰여있다. 이 숫자를 모두 합해서 출력하는 프로그램을 작성하시오.
		Scanner scan = new Scanner(System.in);
		//숫자 갯수
		int N = scan.nextInt();
		//더할 숫자
		String plusNum = scan.next();
		//더한 결과
		int res = 0;
		
		if(N == 1) {
			System.out.println(plusNum);
		}
		else {
			String[] number = plusNum.split("");
			for(int i=0; i<number.length; i++) {
				res = res + Integer.parseInt(number[i]);
			}
			System.out.println(res);
		}
	} 
}

 

11721. 열 개씩 끊어 출력하기

변수를 하나 두고, 반복문 안에서 계속 증가시키면서 10으로 나눈 값이 0일때마다 줄바꿈을 추가해주었다.

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		String str = scan.next();
		
		String[] splitStr = str.split("");
		int enter = 0;
		
		for(int i=0; i<splitStr.length; i++) {
			System.out.print(splitStr[i]);
			++enter;
			if(enter % 10 == 0) {
				System.out.println();
			}
		}
	} 
}

 

15552. 빠른 A + B

Java를 사용하고 있다면, Scanner System.out.println 대신 BufferedReader BufferedWriter를 사용할 수 있다. BufferedWriter.flush는 맨 마지막에 한 번만 하면 된다.

첫 줄에 테스트케이스의 개수 T가 주어진다. T는 최대 1,000,000이다. 다음 T줄에는 각각 두 정수 A와 B가 주어진다. A와 B는 1 이상, 1,000 이하이다.

 

BufferedReader 클래스는 일반적으로 라인단위로 입력을 받게 되며, 라인 바이 라인으로 입력값의 경계를 인식하기 때문에 한줄에 공란을 경계로 여러 값이 입력된 경우라면 파싱이 필수적이다.

입력받은 값은 String 타입이기 때문에 하나하나 타입변환을 해줘야 한다.

BufferedReader는 Scanner처럼 자체적으로 Exception에 대한 처리가 되어 있지 않아서, throws Exception 혹은 try ~ catch 를 이용해서 Exception을 따로 처리해줘야 한다.

그럼에도 BufferedReader를 사용하는 이유는 바로 빠른 속도 때문이다.

[참고해보기] https://code0xff.tistory.com/5


일단, 라인 단위로만 읽어들이기 때문에 공백 단위로 데이터를 나누려면 (1) StringTokenizer (2) split 해주어야하는데 split이 더 익숙해서 이를 이용해 데이터를 공백 기준으로 나누어 배열에 넣어주었다.

참고로, bw.write에는 System.out.println();과 같이 자동개행기능이 없기 때문에 \n를 통해 따로 처리해주었다.

Buffer에 대해 잘 모르겠어서 다른 블로그를 참고하면서 풀었다. 관련된 부분을 공부해야겠다.

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) {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		try {
			int readNum = Integer.parseInt(br.readLine());
			for(int i=1; i<=readNum; i++) {
				String[] resArr = br.readLine().split(" ");
                bw.write(Integer.parseInt(resArr[0]) + Integer.parseInt(resArr[1]) + "\n");
			}
			bw.flush();//남아있는 데이터를 모두 출력시킴
			bw.close();//스트림을 닫음
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	} 
}