有什么方法可以使其更有效/减少循环量

  • 本文关键字:循环 有效 方法 可以使 java
  • 更新时间 :
  • 英文 :


给定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("#");
            }
        }
    }
}

使用Java 11,您可以将String#repeat用于使用单个循环的有效解决方案:

public static void staircase(int n) {
    for (int i = 1; i <= n; i++) {
        System.out.println(" ".repeat(n - i) + "#".repeat(i));
    }
}

我们要做的就是计算特定 line所需的空间量,然后所需的#字符数就是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);
}

最新更新