Count and Say
Problem
The count-and-say sequence starts with 1. Each next term describes the previous term by counting groups of equal digits: 1 is read as one 1, so the next term is 11; 11 is two 1s, so 21; 21 is one 2 and one 1, so 1211. Read n and print the n-th term.
Constraints
- 1 <= n <= 30
Examples
Input
4
Output
1211
Solutions
The terms grow by about 30 percent each step, so n is limited to 40 to keep the output readable. Only the digits 1, 2 and 3 ever appear.
/*
* Problem : The n-th term.
* Input : One integer n.
* Output : The term.
* Approach: Group and say.
* Time : O(length of all terms)
* Space : O(length)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(long n) {
// Step 1: The first term is 1. Build every next term from the one before.
String term = "1";
for (long step = 1; step < n; step++) {
StringBuilder next = new StringBuilder();
int start = 0;
while (start < term.length()) {
// Step 2: Find the end of the group of equal digits that begins at start.
int end = start;
while (end < term.length() && term.charAt(end) == term.charAt(start)) {
end++;
}
// Step 3: Say the count first, then the digit.
next.append(end - start).append(term.charAt(start));
start = end;
}
term = next.toString();
}
return term;
}
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong();
System.out.println(solve(n));
}
}
Hints (1)
- How can you tell that digits above 3 never appear?