countAndSay with JavaScript


  • 0
    N
    /**
     * @param {number} n
     * @return {string}
     */
    var countAndSay = function(n) {
        let output = ['1'];
    
        const parse = (numStr) => {
            let parsedNum = '';
            let c = 1;
            for(let i = 0; i < numStr.length; i += 1) {
                if(numStr[i] === numStr[i + 1]) {
                    c += 1;
                } else {
                    parsedNum += `${c}${numStr[i]}`;
                    c = 1;
                }
            }
    
            return parsedNum;
        };
    
    
        let i = 1;
        while(i < n) {
            output[i] = parse(output[i - 1]);
            i += 1;
        }
    
        return output[n -1];
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.