알고리즘

[백준] 입출력 - 10991번, 별 찍기 16

hatch 2023. 3. 21. 10:38
728x90
반응형

* 공부 목표

입출력 - 2557, 1000, 2558, 1095010951, 10952, 1095311021, 11022, 11718, 1171911720, 117212741, 2742, 27391924, 8393, 108182438, 2439, 24402441, 244224452522, 2446, 10991, 10992

 

  • 10991번

문) 예제를 보고 규칙을 유추한 뒤에 별을 찍어 보세요.

출) 첫째 줄부터 N번째 줄까지 차례대로 별을 출력한다.

 

1. Scanner

import java.util.*;

public class Main{
    public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		int num = sc.nextInt();
		sc.close();
		String[] star = new String[num];
		for(int i=1; i<num+1; i++) {
			star[i-1] = " ".repeat(num-i) + "* ".repeat(i);	
		}
		for(int i=0; i<num; i++) {
			System.out.println(star[i]);
		}
	}
}

 

2. Br + Bw // Scanner에 비해 메모리도 적게, 시간도 절반 정도 소요.

 - 다른 분들 풀이 보니, 배열 안 쓰고 바로 출력하는 방향.

import java.util.*;
import java.io.*;

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 num = Integer.parseInt(br.readLine());
		br.close();
		String[] star = new String[num];
		for(int i=1; i<num+1; i++) {
			star[i-1] = " ".repeat(num-i) + "* ".repeat(i);	
		}
		for(int i=0; i<num; i++) {
			bw.write(star[i] + "\n");
		}
		bw.flush();
		bw.close();
	}
}