java使用array打印金字塔数列?
要求输入一个整数n >= 0,输出[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 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("]");
}
}
回答:
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;
}
已解决
回答:
这段循环,i
不变,j
变化,对同一个 ser[i]
反复赋值。
for (int i = 0; i <= l - 1; i++) { int j = 1;
do {
ser[i] = j;
j++;
} while (j <= i);
}
可以改成
int k = 0;for (int i = 1; i <= n; i++) {
for (int j = 1; i <= i; j++) {
ser[k] = j;
k++;
}
}
以上是 java使用array打印金字塔数列? 的全部内容, 来源链接: utcz.com/p/944765.html