-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcountAndSay.js
More file actions
executable file
·37 lines (35 loc) · 888 Bytes
/
countAndSay.js
File metadata and controls
executable file
·37 lines (35 loc) · 888 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
Given an integer n, generate the nth sequence.
*/
var countSay=function countSay(n) {
if (n<=0) {
return null;
}
var result="1";
var i=1;
while (i<n) {
var sb="";
var count=1;
for (var j=1; j<result.length; j++) {
if (result[j]===result[j-1]) {
count++;
}
else {
sb=sb.concat(count);
sb=sb.concat(result[j-1]);
count=1;
}
}
sb=sb.concat(count);
sb=sb.concat(result[result.length-1]);
result=sb;
i++;
}
return result;
};
console.log(countSay(3));
console.log(countSay(4));
console.log(countSay(5));
console.log(countSay(10));