코딩테스트

[프로그래머스/JAVA] 코딩 기초 트레이닝 > 문자열 반복해서 출력하기

데메즈 2025. 7. 14. 15:35
반응형

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        int n = sc.nextInt();
        String result = "";
        
        for(int i=0; i<n; i++){
            result = result + str;
        }
        System.out.println(result);
    }
}

 


다른 풀이

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        int n = sc.nextInt();
        System.out.println(str.repeat(n));
    }
}

- repeat() 이라는 함수는 몰랐다.

 

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        int n = sc.nextInt();
        StringBuilder sb = new StringBuilder();
        for(int i=0; i<n; i++){
            sb.append(str);
        }
        String s = sb.toString();
        System.out.println(s);
    }
}

- append() 쓸 생각은 못했다.

import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        int n = sc.nextInt();

        for(int i=0;i<n;i++){
        System.out.print(str);
        }
    }
}

- 그냥 print()하면 줄바꿈이 안되는구나

반응형