zoukankan      html  css  js  c++  java
  • 打印金字塔 (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();   // 每一行打印完,需要换行
            }
        }
    }
  • 相关阅读:
    03 . 前端之JavaScipt
    01 . 前端之HTML
    14 . Python3之MysSQL
    13 . Python3之并发编程
    01 . 消息队列之(Kafka+ZooKeeper)
    01 . 分布式存储之FastDFS简介及部署
    03 . Redis集群
    02 . Redis哨兵
    01 . RabbitMQ简介及部署
    01 . Redis简介及部署主从复制
  • 原文地址:https://www.cnblogs.com/sugerandmaster/p/11489835.html
Copyright © 2011-2022 走看看