Problem Description
輸入n值,打印下列形狀的金字塔,其中n代表金字塔的層數。
Input
輸入只有一個正整數n。
Output
打印金字塔圖形,其中每個數字之間有一個空格。
Sample Input
3
Sample Output
1
1 2 1
1 2 3 2 1
Hint
Source
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); for (int i = 0; i < n; i++) { // 共有n行
int k = 0; // 設置變量保存打印的數字
for (int j = 0; j < 2*n+2*i-1; ) { // 前2n+2i-1列為有效列
if (j < 2*n - 2*i - 2) { // 每行需要打印空格的列
System.out.print(" "); j++; } else if (j >= 2*n - 2*i - 2&& j < 2*n-1) { // 每行需要打印遞增數的列
if (i == 0){ // 進行判斷,防止行末空格
System.out.print(++k); } else{ System.out.print(++k+" "); } j += 2; // 因為每個數自帶空格,所以占兩列
} else { if (k == 2){ // 進行判斷,防止行末空格
System.out.print(--k); } else{ System.out.print(--k+" "); } j += 2; } } System.out.println(); // 每一行打印完,需要換行
} } }
