Reputation:
Given an int n, print a staircase using #. This is from hacker rank, staircase problem. example: n = 4.
output:
#
##
###
####
whereas each row has the same amount of columns but the # signs increase and the space decrease as we keep going through the rows.
I've solved the problem, just trying to see if there is a more efficient way
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("#");
}
}
}
}
Upvotes: 1
Views: 98
Reputation: 29730
Using Java 11, you can utilize String#repeat
for an efficient solution that uses a single for-loop:
public static void staircase(int n) {
for (int i = 1; i <= n; i++) {
System.out.println(" ".repeat(n - i) + "#".repeat(i));
}
}
All we do is calculate the amount of spaces that are needed for the specific line, and then the number of #
characters needed is simply n
minus the amount of spaces used.
If n
is a large value, you can build a String
(using a StringBuilder
) and then print it instead of calling System.out.println
n
times:
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);
}
Upvotes: 8