The Count and Say Sequence
The "Count and Say" sequence is a fascinating way to generate strings based on descriptions of the previous string. This problem challenges you to implement a function that generates the nth term of this sequence. Understanding and implementing this sequence is a good exercise in string manipulation and iterative generation.
Problem Description
The "Count and Say" sequence is defined recursively. The first term of the sequence is simply "1". To generate the next term, you "read aloud" the previous term, counting the occurrences of consecutive identical digits.
For example:
- The first term is "1".
- The second term is "one 1", which is written as "11".
- The third term is "two 1s", which is written as "21".
- The fourth term is "one 2, one 1", which is written as "1211".
- The fifth term is "one 1, one 2, two 1s", which is written as "111221".
Your task is to write a function that, given an integer n, returns the nth term of the "Count and Say" sequence.
Key Requirements:
- The function should accept a single integer
nas input. - The function should return a string representing the nth term of the sequence.
- The sequence starts with
n=1.
Examples
Example 1:
Input: 1
Output: "1"
Explanation: The first term is always "1".
Example 2:
Input: 4
Output: "1211"
Explanation:
- n=1: "1"
- n=2: read "1" as "one 1" -> "11"
- n=3: read "11" as "two 1s" -> "21"
- n=4: read "21" as "one 2, one 1" -> "1211"
Example 3:
Input: 5
Output: "111221"
Explanation:
- n=4: "1211"
- n=5: read "1211" as "one 1, one 2, two 1s" -> "111221"
Constraints
- 1 <= n <= 30
- The input
nwill be an integer. - The output string will only contain digits ('0'-'9').
Notes
Consider how you will iterate through the string to count consecutive characters. You'll need a way to keep track of the current character and its count, and then append this information to the new string being built. Think about handling the end of a string when processing characters.