Java 문제: 숫자 피라미드 쌓기

조회수 2933회

안녕하세요 과제하다가 제 코드가 마음에 안들어서 질문드립니다.

교수님께서 주신 문제는 다음과 같습니다.

Develop a JAVA-program that does the following job:
    Your program shall ask the user for the input of some integer num. 
    Subsequent to the input, your program shall print a pyramid like
    described below.
    Each line consists of three parts.
    The first part comprises some spaces for formatted output; 
    the second part, some leading numbers, such as 3 2 1 on line 3; 
    and the last part, some ending numbers, such as 2 3 on line 3.
    So, the output should look as follows:

    ex) input: 5

        1
       212
      32123
     4321234
    543212345

 

과제로 제출한 제 코드입니다.

package kr.co.hashcode;

import java.util.Scanner;

public class Question4 {
    public static void main(String[] args) {
        int counter;
        int i, j, k;

        Scanner scan = new Scanner(System.in);

        System.out.printf("Input integer value: ");
        counter = scan.nextInt();        
        System.out.printf("\n");
        scan.close();

        for (i = 0; i < counter; i++) {
            for (j = 0; j < counter-i-1; j++) {
                System.out.printf(" ");
            }
            k = i + 1;
            for (j = 0; j < i; j++) {
                System.out.printf("%d", k--);
            }
            k = 1;
            for (j = 0; j < i+1; j++) {
                System.out.printf("%d", k++);
            }
            System.out.printf("\n");
        }
    }
}

 

작동은 잘 되는데 복학하기 전에 배운거라 기억은 잘 안나지만 시간복잡도 O(n²)(?)인 코드라서 마음에 안듭니다. 과제는 오늘 제출하긴 했는데 혹시 이 코드를 더 간단하게 작성할 수 있을까요?

2 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    자바

    public class Main {
        public static void main(String[] args) {
            int n = 7;
            String line = "";
            for(int i = 1; i <= n; i++) {
                line = i == 1 ? String.valueOf(i) : String.valueOf(i) + line + String.valueOf(i);
                //String.format("%3s%s", "", "12321"); //"   12321"
                String reg = i == n ? "%s%s" :"%" + String.valueOf(n - i) + "s%s";
                System.out.println(String.format(reg, "", line));
            }
        }
    
    }
    
          1
         212
        32123
       4321234
      543212345
     65432123456
    7654321234567
    
    • "%" + String.valueOf(n - i) + "s%s" 라고 쓸 수도 있군요! 감사합니다 Hommy 2018.4.6 10:40
  • 파이썬 입니다.

    n = 7
    line = ''
    for i in range(1, n + 1):
        line = str(i) if i == 1 else str(i) + line + str(i)
        print(' ' * (n - i) + line)
    
    
          1      
         212     
        32123    
       4321234   
      543212345  
     65432123456 
    7654321234567
    
    
    • 제가 현재 배우는 과목이 자바여서 이 답변을 채택하지 않았는데 정말 간단하네요... 5줄... Hommy 2018.4.6 10:43

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)