본문 바로가기
코딩테스트/백준

JAVA 백준 2558번 A+B - 2

by 광고(주) 2022. 7. 23.
반응형

문제

두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.

입력

첫째 줄에 A, 둘째 줄에 B가 주어진다. (0 < A, B < 10)

출력

첫째 줄에 A+B를 출력한다.

예제 입력 1 

1
2

예제 출력 1 

3

알고리즘 분류

구현(implementation), 사칙연산(arithmetic), 수학(math)

소스코드

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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int T = Integer.parseInt(br.readLine());

        for (int i = 0; i < T; i++) {
            int n = Integer.parseInt(br.readLine());
            System.out.println(call(n));
        }
    }

    public static int call(int n) {
        switch (n) {
            case 1:
                return 1;
            case 2:
                return 2;
            case 3:
                return 4;
        }
        int[] cache = new int[n + 1];
        cache[1] = 1;
        cache[2] = 2;
        cache[3] = 4;
        for (int index = 4; index <= n; index++) {
            cache[index] = cache[index - 1] + cache[index - 2] + cache[index - 3];
        }
        return cache[n];
    }
}

 

반응형

댓글