用java实现如下:
方法一:
方法二:递归
方法三:二维数组
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
方法一:
private static void pyramid(int line) {
for(int i=1; i<=line; i++) {
for(int j=1; j<=line-i; j++) {
System.out.print(" ");
}
boolean flag = true;
int l = 0;
for(int k=1; flag?k<=i:k>=1; l=flag?k++:k--) {
System.out.print(k);
if(k == i) {
flag = false;
}
}
System.out.println();
}
}
方法二:递归
private static void pyramid(int currentLine, int maxLine) {
if(currentLine == maxLine) {
return;
}
int column = 0;
int num = 0;
while(column < 2*currentLine - 1) {
if(column == 0) {
for(int i=1; i<maxLine-currentLine; i++) {
System.out.print(" ");
}
}
if(column < currentLine) {
System.out.print(++ num);
} else {
System.out.print(-- num);
}
column ++;
}
System.out.println();
pyramid(++ currentLine, maxLine);
方法三:二维数组
private static void pyramid(int maxLine) {
int[][] arr = new int[maxLine][];
for(int i=0; i<arr.length; i++) {
arr[i] = new int[2*i+1];
int num = 0;
for(int j=0; j<arr[i].length; j++) {
if(j <= i) {
arr[i][j] = ++ num;
} else {
arr[i][j] = --num;
}
}
}
for(int i=0; i<arr.length; i++) {
for(int k=1; k<maxLine-i; k++) {
System.out.print(" ");
}
for(int j=0; j<arr[i].length; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}
}