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 답변
-
자바
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
-
파이썬 입니다.
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
댓글 입력