Why my code is slow (javascript)?


  • 0
    T

    I use as less loops as I can, but it still seems to be slow (only beats 50% codes). I don't know how to improve the performance..

     /**
     * @param {number} num
     * @return {string}
     */
    var numberToWords = function(num) {
        if(num === 0) {
            return "Zero";
        }
        
        
        var num1 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", 
                    "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
        var num2 = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
        
        var numStr = num.toString();
        var result = [];
        var digit = 1;
        
        for(var i=numStr.length-1;i>=0;i--) {
            switch(numStr.length - i) {
                case 4:
                    if(!numStr[i-2]) {
                        result.unshift("Thousand");
                        break;
                    }
                    if(Number(numStr.substring(i-2, i+1)) !== 0) {
                        result.unshift("Thousand");
                        break;
                    }
                    break;
                case 7:
                    if(!numStr[i-2]) {
                        result.unshift("Million");
                        break;
                    }
                    if(Number(numStr.substring(i-2, i+1)) !== 0) {
                        result.unshift("Million");
                        break;
                    }
                    break;
                case 10:
                    result.unshift("Billion");
            }
            
            switch(digit) {
                case 1:
                    if(numStr[i] === "0") {
                        break;
                    }
                    if(numStr[i-1] !== "1") {
                        result.unshift(num1[Number(numStr[i])]);
                    }
                    break;
                case 2:
                    if(numStr[i] === "0") {
                        break;
                    }
                    if(numStr[i] === "1") {
                        result.unshift(num1[Number(numStr.substring(i, i+2))]);
                    } else {
                        result.unshift(num2[Number(numStr[i])]);
                    }
                    break;
                case 3:
                    if(numStr[i] === "0") {
                        break;
                    }
                    result.unshift("Hundred");
                    result.unshift(num1[Number(numStr[i])]);
                    break;
            }
            
            if(digit === 3) {
                digit = 1;
            } else {
                digit++;
            }
        }
        
        return result.join(" ");
    };

Log in to reply
 

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