商城首页欢迎来到中国正版软件门户

您的位置:首页 >Java数组打印金字塔数列:如何创建1,2,3…n数组?

Java数组打印金字塔数列:如何创建1,2,3…n数组?

  发布于2025-07-16 阅读(0)

扫一扫,手机访问

java使用array打印金字塔数列

问题:

要求编写一个方法,给定一个整数n,生成一个包含[1,1,2,1,2,3,..... 1, 2, 3,…n]元素的array,array长度为1 2 3… n=n*(n 1)/2。比如:arithseries(3) → [1, 1, 2, 1, 2, 3]

代码:

public static int[] arithSeries(int n) {
    int resultLength = n * (n + 1) / 2; // length of result array
    int[] result = new int[resultLength]; // initialise array
    int pointer = 0; // the position of array
    for (int i = 1; i <= n; i++) { // if i start from 1 then the end condition should be <=n
        for (int j = 1; j <= i; j++) {// assign value from 1 to i
            result[pointer] = j;
            pointer++;// move to next pointer
        }
    }
    return result;
}
本文转载于:互联网 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注