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));

1 comment:

  1. buy 5- 9H-carbazol-3-yl pentanoic acid - Alfa Chemistry offers an extensive catalog of lipids in a wide range of applications. Products listed on our website are either in stock or can be resynthesized within a reasonable time frame. In stock products can be shipped out within 3-5 business days upon receipt of customers' purchase order.

    ReplyDelete

Blogroll

Popular Posts