java使用array打印金字塔数列?
要求输入一个整数n >= 0,输出[1,1,2,1,2,3,..... 1, 2, 3,…n]的arrayarray的长度为1 + 2 + 3…+ n=n*(n + 1)/2比如:arithSeries(3) → [1, 1, 2, 1, 2, 3]
我的代码如下,无法打印上面的结果,请求指正
public static void main(String[] args) {
printInts(arithSeries(3));
}
public static int[] arithSeries(int n) {
int l = (n*(n+1))/2;
int[] ser = new int[l];
for (int i = 0; i <= l-1; i++) {
int j = 1;
do{
ser[i]=j;
j++;
}while (j<=i);
}
return ser;
}
public static void printInts(int[] ser){
System.out.print("[");
for (int i=0;i<ser.length;i++){
if (i != ser.length-1){
System.out.print(ser[i]+", ");
}
else {
System.out.print(ser[i]);
}
}
System.out.print("]");
}
}
回复
1个回答

test
2024-07-18
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;
}
已解决
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容