如何用数字制作金字塔图案?

  • 本文关键字:金字塔 何用 数字 java
  • 更新时间 :
  • 英文 :


如何在java中用递归制作这个金字塔?

1
222
33333
4444444
.
.
.

我做了这个模式,但行数增加了 1 而不是 2

static void recursion(int row, int k, int j,int c){
if(row>c){
return;
}
else{
if(k==row){
System.out.println();
recursion(++row, 0,0,c);
}
else if(c-j>row){
System.out.print(" ");
++j;
recursion(row, k, j,c);
}
else{
System.out.print(row+" ");
recursion(row, ++k, j,c);
}   
}

结果:

1 
2 2 
3 3 3 
4 4 4 4 
5 5 5 5 5 

这是一个使用您现有设计逻辑的解决方案,或者按照我的理解。我更改了一些变量名称,以便我能记住什么做了什么。(编码时使用有意义的名称(

recursion(1, 0, 0, 7);

static void recursion(int row, int space, int num, int total){
if (space < total-row){
System.out.print(' ');
if (total > 9) System.out.print(' ');
recursion(row, ++space, num, total);
}else if(num < row*2-1){
String r = (row < 10 && total > 9)?" "+row:""+row;
System.out.print(r);
recursion(row, space, ++num, total);
}else{
System.out.println();
recursion(++row, 0, 0, total);
}
}
}

试试这个。

static void pyramid(int n, int i) {
if (i > n) return;
System.out.println(" ".repeat(n - i) + Integer.toString(i).repeat(i * 2 - 1));
pyramid(n, i + 1);
}

pyramid(5, 1);

结果:

1
222
33333
4444444
555555555

最新更新