My solution in JavaScript. Very easy to understand.


  • 0
    L
    /**
     * @param {number} num
     * @return {string}
     */
    var numberToWords = function(num) {
        if (num === 0) {
            return 'Zero';
        }
    
        if (num < 0) {
            return 'Negative ' + chunks_to_string(split_into_chunks(-num));
        }
    
        return chunks_to_string(split_into_chunks(num));
    };
    
    // make the number into chunks divided by 1000.
    var split_into_chunks = function(num) {
        var chunks = [];
        while (num > 0) {
            chunks = [num % 1000].concat(chunks);
            num = parseInt(num / 1000);
        }
        return chunks;
    };
    
    var chunks_to_string = function(chunks) {
        var scales = [' Quadrillion', ' Trillion', ' Billion', ' Million', ' Thousand', ''];
        var zero_to_nineteen = ['Zero',  'One',  'Two',  'Three',  'Four',  'Five', 'Six', 'Seven', 'Eight',  'Nine',  'Ten',  'Eleven', 'Twelve', 'Thirteen',  'Fourteen', 'Fifteen', 'Sixteen',  'Seventeen', 'Eighteen', 'Nineteen'];
        var tens = {2: 'Twenty', 3: 'Thirty', 4: 'Forty', 5: 'Fifty', 6: 'Sixty', 7: 'Seventy', 8: 'Eighty', 9: 'Ninety'};
    
        var strs = [];
    
        // translate every chunk into English words.
        // After this loop we have a new array whose elements are English represented numbers less than 1000.
        for (var i in chunks) {
            strs[i] = '';
            if (chunks[i] >= 100) {
                strs[i] = zero_to_nineteen[parseInt(chunks[i]/100)] + ' Hundred';
                if (chunks[i] % 100 === 0) {
                    continue;
                } else {
                    strs[i] += ' ';
                }
            }
            chunks[i] = chunks[i] % 100;
            if (chunks[i] >= 20) {
                strs[i] += tens[parseInt(chunks[i]/10)];
                if (chunks[i] % 10 === 0) {
                    continue;
                } else {
                    chunks[i] = chunks[i] % 10;
                    strs[i] += ' ';
                }
            }
            strs[i] += zero_to_nineteen[chunks[i]];
        }
    
    
        // Now we join the array we just made with spaces. Inner 'Zero's should be ignored.
        var temp_array = [];
        while (strs.length > 0 && scales.length > 0) {
            str = strs.pop();
            scale = scales.pop();
            if (str == 'Zero') {
                continue;
            }
            temp_array = [].concat(str + scale, temp_array);
        }
        return temp_array.join(' ');
    };
    
    

Log in to reply
 

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