Jakorithm
article thumbnail
728x90

문제

https://www.codetree.ai/training-field/search/problems/recursive-function-that-outputs-string?&utm_source=clipboard&utm_medium=text

 

코드트리 | 코딩테스트 준비를 위한 알고리즘 정석

국가대표가 만든 코딩 공부의 가이드북 코딩 왕초보부터 꿈의 직장 코테 합격까지, 국가대표가 엄선한 커리큘럼으로 준비해보세요.

www.codetree.ai

 

 

정수 n이 주어지면 횟수 n 만큼 Coding is my favorite hobby!를 출력하는 프로그램을 재귀함수를 이용해 작성해보세요.

 

입력 예시

4

 

출력 예시

Coding is my favorite hobby!
Coding is my favorite hobby!
Coding is my favorite hobby!
Coding is my favorite hobby!

 

 

코드

첫 번째 줄에 정수 n이 주어진다.

  • 1 <= n <= 100
import java.io.*;

public class Main {
    static final String str = "Coding is my favorite hobby!";
    static int n;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        n = Integer.parseInt(br.readLine());

        StringBuilder sb = new StringBuilder();
        printRecursive(0, str, sb);

        bw.write(sb.toString());
        bw.flush();
    }

    private static void printRecursive(int count, String str, StringBuilder sb) {
        if (count == n) {
            return;
        }
        sb.append(str).append("\n");
        printRecursive(count + 1, str, sb);
    }
}
728x90