使用 java 数组打印金字塔数列
在 java 中打印从 1 到 n 的金字塔数列可以使用数组实现。具体步骤如下:
- 计算数组长度:金字塔数列的数组长度为 1 2 3 ... n,即 n*(n 1)/2。
- 初始化数组:创建一个指定长度的数组 ser 来存储金字塔数列。
- 遍历数组:使用循环遍历数组,依次生成金字塔数列。
- 生成数列:内部循环中,将 ser[i] 赋值为 j,然后 j 自增,直到 j > i。
- 打印结果:遍历 ser 数组,打印金字塔数列。
示例代码:
import static java.util.Arrays.toString;
public class Solution {
public static void main(String[] args) {
int[] series = arithSeries(5);
System.out.println(toString(series)); // [1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5]
}
public static int[] arithSeries(int n) {
int l = (n * (n + 1)) / 2;
int[] ser = new int[l];
int pointer = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
ser[pointer] = j;
pointer++;
}
}
return ser;
}
}











