878899. Inverted Right AngleTriangle
Basic
Inverted Right Angle Triangle
Summary
The problem involves generating an inverted right-angle triangle where each row has a specific number of stars. The number of stars in each row increases by one, and the remaining spaces are filled with underscores. For example, if the input is 5, the output would be:
_____
***
__*
_*
*
Detailed Explanation
To solve this problem, we can use a simple loop to generate the triangle. We start from the last row (the smallest number of stars) and move upwards.
Here's the step-by-step breakdown:
- Start with an empty string
resultthat will store the final output. - Loop through each row from the smallest to the largest, using a variable
ito represent the current row. - For each row, calculate the number of stars and underscores needed based on the value of
i. - Append the required number of stars and underscores to the
resultstring. - Move on to the next row by incrementing
i.
Time complexity: O(n), where n is the input number.
Space complexity: O(1), as we only use a constant amount of space to store the result.
Optimized Solutions
Java
public class Main {
public static void main(String[] args) {
int n = 5; // input number
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
if (j == i) {
sb.append("*");
} else {
sb.append("_");
}
}
sb.append("\n");
}
System.out.println(sb.toString());
}
}