Alternating Binary Triangle
Problem
Read n and print a triangle of 1 and 0 without spaces. Every row starts with 1 and the digits alternate. Row 1 is 1, row 2 is 10, row 3 is 101, and so on.
Constraints
- 1 <= n <= 30
Examples
Input
3
Output
1 10 101
Solutions
Each row is the first row digits of the sequence 1010101... The remainder of the position divided by 2 chooses 1 or 0.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write " ".repeat(count).
/*
* Problem : Alternating digits triangle.
* Input : One integer n (rows).
* Output : n lines.
* Approach: Digits at even positions are 1, at odd positions are 0.
* 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++) {
StringBuilder line = new StringBuilder();
// Step 2: Write "row" digits. Position 0 is the first digit of the row.
for (int position = 0; position < row; position++) {
// Step 3: Even positions (0, 2, 4) give 1. Odd positions (1, 3, 5) give 0.
line.append(position % 2 == 0 ? "1" : "0");
}
// Step 4: Print the finished line.
System.out.println(line);
}
}
}
Hints (2)
- Use an outer loop for rows and an inner loop for the letters or digits.
- Write the output for n = 3 and look for the rule.