The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
一开始不想做这道题,觉得没啥意思,后来还是做了,确实没啥意思。。。
var countAndSay = function(n) {
var now = "1";
var result = "";
while (n!==1) {
var p = now[0];
var count = 0;
for (var i = 0; i<now.length;i++) {
if (now[i]===p) {
count++;
} else {
result+=count;
result+=p;
p=now[i];
count = 1;
}
}
result+=count;
result+=p;
now = result;
result = "";
n--;
}
return now;
};