1 java
给定一个int n,使用#打印一个楼梯。这是从黑客的角度出发,楼梯出现的问题。例如:n = 4。
输出:
#
##
###
####
Run Code Online (Sandbox Code Playgroud)
而每行具有相同数量的列,但是随着我们不断浏览行,#号增加而空间减小。
我已经解决了这个问题,只是想看看是否有更有效的方法
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("#");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用Java 11,可以利用String#repeat一个有效的解决方案,该解决方案使用单个for循环:
public static void staircase(int n) {
for (int i = 1; i <= n; i++) {
System.out.println(" ".repeat(n - i) + "#".repeat(i));
}
}
Run Code Online (Sandbox Code Playgroud)
我们要做的只是计算特定行所需的空格数量,然后#所需的字符数就是n减去所使用的空格数量。
如果n值较大,则可以构建一个String(使用StringBuilder),然后打印它而不是调用System.out.println n时间:
public static void staircase(int n) {
var sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
sb.append(" ".repeat(n - i)).append("#".repeat(i)).append('\n');
}
System.out.print(sb);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |