Reverse Number Triangle
Problem
Read n and print an upside-down triangle. Row 1 has the numbers 1 to n, row 2 has 1 to n-1, and the last row has only 1.
Constraints
- 1 <= n <= 20
Examples
Input
3
Output
1 2 3 1 2 1
Solutions
The number of values in a row goes down by one each time: n - row + 1. Every row still starts from 1.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write " ".repeat(count).
/*
* Problem : Upside-down number triangle.
* Input : One integer n (rows).
* Output : n lines of numbers.
* Approach: Each row is one number shorter than the row before.
* Time : O(n^2)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int rows = new Scanner(System.in).nextInt();
// Step 1: Repeat once for each row. Row numbers go from 1 to rows.
for (int row = 1; row <= rows; row++) {
// Step 2: Count how many numbers this row has. Row 1 has n numbers, the last row has 1.
int count = rows - row + 1;
StringBuilder line = new StringBuilder();
// Step 3: Write the numbers 1, 2, ... up to the count.
for (int number = 1; number <= count; number++) {
if (number > 1) {
line.append(" ");
}
line.append(number);
}
// Step 4: Print the finished line.
System.out.println(line);
}
}
}
Hints (2)
- Use an outer loop for the rows and an inner loop for the numbers in a row.
- Write the output for n = 3 and look for the rule.