Question
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1
Is read off"one 1"
Or11
.
11
Is read off"two 1s"
Or21
.
21
Is read off"one 2
, Thenone 1"
Or1211
.
Given an integerN, GenerateNTh sequence.
Note: The sequence of integers will be represented as a string.
Direct Simulation
Code:
Class Solution {public: string toString (int n) // convert the number to string {string ans; int radix = 1; while (n/radix> 9) radix * = 10; while (radix> 0) {ans. push_back ('0' + n/radix); n % = radix; radix/= 10;} return ans;} string countAndSay (int n) {string ans = "1 ", temp; int I, j, k, len; for (I = 1; I <n; I ++) // directly simulate {len = ans. size (); j = 0; while (j <len) {k = j + 1; while (k <len & ans [k] = ans [j]) k ++; temp + = toString (k-j); temp. push_back (ans [j]); j = k;} ans = temp; temp. clear () ;}return ans ;}};