我陷入了以下模式,寻求任何帮助。
我无法使用三元运算符为底部编写正确的代码,我已经看到了许多其他以 diff 格式提供的代码,但是我想使用三元操作来做到这一点。 任何帮助都更加值得赞赏。
i/pn=5
预期产出
12345
2345 ===upper part
345
45
5
45
345
2345
12345
我得到的输出:
1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
6 7
7 8
8 9 ===bottom part
9 10
10 11
我尝试使用三元运算符来解决它,但没有成功
static void pattern(int n) {
for (int i = 1; i <= 2 * n; i++) {
int colInRows = i <= n ? n : (i + 1);
int spacesInRows = i <= n? 1: (i - n)+2;
for (int j = i ; j > spacesInRows ; j--) {
System.out.print(" ");
}
for (int k=i ; k <= colInRows ; k++){
System.out.print(k + " ");
}
System.out.println();
}
}
在我看来,最好的方法是将数字转换为字符串。 而且你只需要一个循环。
int n = 12345;
String s = Integer.toString(n);
int len = s.length();
for(int i = 0; i < len*2-1; i++) {
String str = i < len-1 ? " ".repeat(i) + s.substring(i) :
" ".repeat(2*len-2-i) + s.substring(2*len-2-i);
System.out.println(str);
}
打印
12345
2345
345
45
5
45
345
2345
12345