Algorithm/[BOJ] - JAVA

[백준] 2448 : 별 찍기 - 11 JAVA 풀이

Codew 2022. 9. 12. 17:48

https://rightbellboy.tistory.com/39

 

[백준/BOJ] 2448번 별찍기 - 11 (java)

백준 온라인 저지(BOJ) 2448번 별찍기 - 11 https://www.acmicpc.net/problem/2448 * 사용언어 : java, 자바 1. 문제 N( = 3 * 2 ^ k(1, 2, ... , 10) )을 입력받고 N번째 줄까지 예제와 같이 별을 출력 2. 풀이..

rightbellboy.tistory.com

이 포스트를 참고해서 풀었다.

설명이 아주 잘 되어 있어서 읽어보면 큰 도움이 될 것이다.

 

import java.io.*;
import java.util.*;
public class Main{
    public static void main(String[] args)throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        // n을 입력받음
        int n = Integer.parseInt(br.readLine());
        
        // n개의 String 배열을 생성함
        String[] str = new String[n];
        // 반복되는 모양을 문자열에 저장함
        str[0] = "  *  ";
        str[1] = " * * ";
        str[2] = "*****";
        
        // Math.pow(밑, 지수)
        // n이 3*2^k인데, 2^k층만큼 일정한
        for(int k=1;3*(int)Math.pow(2,k)<=n;k++){
            star(k, str);
        }
        
        // 완성된 패턴을 출력함
        for(int i=0;i<n;i++){
            System.out.println(str[i]);
        }
    }
    
    // 패턴을 만드는 함수
    // 인자로 k와 String 배열을 받음
    public static void star(int k, String[] str){
    
        int bottom = 3*(int)Math.pow(2,k);
        int middle = bottom/2;
        
        for(int i=middle;i<bottom;i++){
            str[i] = str[i-middle]+" "+str[i-middle];
        }
        String space = "";
        while(space.length()<middle){
            space +=" ";
        }
        for(int i=0;i<middle;i++){
            str[i] = space+str[i]+space;
        }
    }
}