【发布时间】:2019-05-23 14:39:38
【问题描述】:
给定一个 int n,使用 # 打印一个楼梯。这是来自黑客等级,楼梯问题。例子: n = 4。
输出:
#
##
###
####
虽然每一行都有相同数量的列,但随着我们不断地遍历行,# 符号会增加,空间会减少。
我已经解决了问题,只是想看看有没有更有效的方法
public static void staircase(int n) {
int spaceCounter = 0;
for(int i = 1; i <= n; i++) { // Takes care of the rows
spaceCounter = n - i;
// Takes care of the column by printing a space until a # sign is required then it would print so.
for (int j = 1; j <= spaceCounter; j++) {
System.out.print(" ");
if (j == spaceCounter) {
//Prints as many #s as needed (n minus the number of spaces needed)
for(int k = 1; k <= (n - spaceCounter); k++) {
System.out.print("#");
}
//makes sure it goes to the next life after being done with each row
System.out.println();
}
}
if (i == n) {
for(int j = 1; j <= n; j++) {
System.out.print("#");
}
}
}
}
【问题讨论】:
-
这更适合codereview.stackexchange.com。我们将在这里修复损坏的代码。
-
由于您的代码目前有效,我相信它属于CodeReview(链接指向他们的如何提问)。
-
对不起,这里有点新,但谢谢你,现在我知道了!
标签: java