打印金字塔 (java实现)

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();   // 每一行打印完,需要换行
        }
    }
}
原文地址:https://www.cnblogs.com/sugerandmaster/p/11489835.html