阅读 64

算法009:金字塔打印问题,特别注意空格

题目:
金字塔打印,三角形
        1 
       2 2 
      3 3 3 
     4 4 4 4 
    5 5 5 5 5 
   6 6 6 6 6 6 
  7 7 7 7 7 7 7 
 8 8 8 8 8 8 8 8 
9 9 9 9 9 9 9 9 9 

思路:
注意空格
复制代码

1.代码如下 Pyramid .java:

package com.yuhl.right;

/**
 * @author yuhl
 * @Date 2020/10/24 23:15
 * @Classname Pyramid
 * @Description 金字塔打印
 *
 */
public class Pyramid {

    public static void main(String[] args) {
        pyramid(9);//9行
    }

    public static void pyramid(int n){//金字塔
        int i,j,k,m;
        m=n;
        for (i=1;i<=m;i++){
            for(j=m-i;j>0;j--)
                System.out.print(" ");
            for(k=1;k<=i;k++)
            {
                System.out.print(i+" ");
            }
            System.out.println();
        }
    }
    /**
     * 递增金字塔
     *         1
     *        2 3
     *       4 5 6
     *      7 8 9 10
     *     11 12 13 14 15
     *    16 17 18 19 20 21
     *   22 23 24 25 26 27 28
     *  29 30 31 32 33 34 35 36
     * 37 38 39 40 41 42 43 44 45
     */
    public static void pyramidIcrehh(int n) {//金字塔
        int step  = 1;
        int i, j, k, m;
        m = n;
        for (i = 1; i <= m; i++) {
            for (j = m - i; j > 0; j--)
                System.out.print(" ");
            for (k = 1; k <= i; k++) {
                System.out.print(step++  + " ");
            }
            System.out.println();
        }
    }


    /**
     * 蛇状变化
     *         1
     *        3 2
     *       4 5 6
     *      10 9 8 7
     *     11 12 13 14 15
     *    21 20 19 18 17 16
     *   22 23 24 25 26 27 28
     *  36 35 34 33 32 31 30 29
     * 37 38 39 40 41 42 43 44 45
     *
     * Process finished with exit code 0
     */
    public static void pyramidSSSS(int n) {//金字塔
        int step  = 1;//
        int line = 0;
        int i, j, k, m;
        m = n;
        for (i = 1; i <= m; i++) {
            for (j = m - i; j > 0; j--)
                System.out.print(" ");

            int temp = 0;
            temp = line + step;
            for (k = 1; k <= i; k++) {
                if (line % 2 == 1) {

                    System.out.print(temp-- + " ");
                    step++ ;
                } else {
                    System.out.print(step++ + " ");
                }
            }
            line ++;
            System.out.println();
        }
    }
}
复制代码

2.执行结果:

"C:\Program Files\Java\jdk1.8.0_201\bin\java.exe" 
        1 
       2 2 
      3 3 3 
     4 4 4 4 
    5 5 5 5 5 
   6 6 6 6 6 6 
  7 7 7 7 7 7 7 
 8 8 8 8 8 8 8 8 
9 9 9 9 9 9 9 9 9 
复制代码
文章分类
后端
文章标签