711657. Pattern 5
Basic
Pattern 5 ==Triangles, anyone?== #711657
Summary
Generate a triangle pattern of asterisks (*) using a given input integer n. The pattern should have n levels. For example, if n is 3, the output would be:
*
***
*****
The problem involves generating a specific pattern based on an input value.
Detailed Explanation
To generate this pattern, we can use a simple algorithm that iterates from level 1 to n. At each level, we print the number of asterisks required for that level. We start with 1 asterisk at level 1, then 3 asterisks at level 2, and so on.
Here's a step-by-step breakdown:
- Initialize an integer variable
ito 1. - Loop until
iis less than or equal ton. - Print
inumber of asterisks (*) followed by a newline character (\n). - Increment
iby 2 for the next iteration.
Time complexity: O(n), as we only iterate n times.
Space complexity: O(1), as we don't use any extra space that scales with input size.
Optimized Solutions
Java
public static void printTriangle(int n) {
int i = 1;
while (i <= n) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
i += 2;
}
}