首页 > 解决方案 > 如何为给定的整数数组列表值执行逆金字塔?在安卓中

问题描述

 4  5  7  6 3
  9  3  4  9
   3  7  4
    1   2
      3

4+5=9

5+7=12 -->1+2=3

同样,如何获得最终结果 3 之类的n数字?

public static void main(String[] args) {        
    int rows = 5;

    for(int i = rows; i >= 1; --i) {
        for(int space = 1; space <= rows - i; ++space) {
            System.out.print("  ");
        }

        for(int j=i; j <= 2 * i - 1; ++j) {
           System.out.print("* ");
            //System.out.print(a[j]);
        }

        for(int j = 0; j < i - 1; ++j) {
            System.out.print("* ");
        }            
    }
}

标签: javaarrayslist

解决方案


代码,前提是数字在数组中,因为我在您提供的数字中找不到模式。

public static void main(String[] args) {

        int numList[] = {4, 5, 7, 6, 3, 9, 3, 4, 9, 3, 7, 4, 1, 2, 3};
        int i,j=0,k=1; //k is for the spaces.

        for (int line = 4; line >= 0; line--) {

            // To display spaces
                for(int space=0; space<k; space++) {
                    System.out.print(" ");

                }
             // To display the numbers.
                for (i = j; i <= (j + line); i++) {
            // The below if statement is for symmetry, you may ignore it.
                    if(k>=1){
                        System.out.print(" ");
                    }
                    System.out.print(" "+numList[i]+" ");
                }
                j = i;
                //The below code is just to make the pyramid symmetrical you
                //may ignore it.
                if(k==0){
                    k++;
                }
                else{
                    k+=2;
                }

                System.out.println();
            }
       }

输出

在此处输入图像描述


推荐阅读