The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

Example 

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.

JavaScript Code

function countAndSay(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.charAt(j) == result.charAt(j - 1)) {
                count++;
            } else {
                sb += count;
                sb += result.charAt(j - 1);
                count = 1;
            }
        }
 
        sb += count;
        sb += result.charAt(result.length - 1);
        result = sb;
        i++;
    }
 
    return result;
}

console.log(countAndSay(3));

0 comments:

Blogroll

Follow this blog by Email

Popular Posts