273. Integer to English Words

Difficulty:
Related Topics:
Similar Questions:

Problem

Convert a non-negative integer num to its English words representation.

  Example 1:

Input: num = 123
Output: "One Hundred Twenty Three"

Example 2:

Input: num = 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input: num = 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

  Constraints:

Solution

/**
 * @param {number} num
 * @return {string}
 */
var numberToWords = function(num) {
    if (num === 0) return 'Zero';
    var words1 = [
        'One',
        'Two',
        'Three',
        'Four',
        "Five",
        "Six",
        'Seven',
        'Eight',
        'Nine',
    ];
    var words2 = [
        'Ten',
        'Eleven',
        'Twelve',
        'Thirteen',
        'Fourteen',
        'Fifteen',
        'Sixteen',
        'Seventeen',
        'Eighteen',
        'Nineteen',
    ];
    var words3 = [
        'Ten',
        'Twenty',
        'Thirty',
        'Forty',
        'Fifty',
        'Sixty',
        'Seventy',
        'Eighty',
        'Ninety',
    ];
    var getStr = function(number) {
        var res = [];
        var num1 = Math.floor(number / 100);
        if (num1 > 0) {
            res.push(`${words1[num1 - 1]} Hundred`);
        }
        number %= 100;
        if (number >= 10 && number <= 19) {
            res.push(words2[number - 10]);
        } else {
            var num2 = Math.floor(number / 10);
            if (num2 > 0) {
                res.push(words3[num2 - 1]);
            }
            number %= 10;
            if (number > 0) {
                res.push(words1[number - 1]);
            }
        }
        return res.join(' ');
    };
    var res = [];
    [
        [Math.pow(10, 9), 'Billion'],
        [Math.pow(10, 6), 'Million'],
        [Math.pow(10, 3), 'Thousand'],
    ].forEach(item => {
        var num1 = Math.floor(num / item[0]);
        if (num1 > 0) {
            res.push(`${getStr(num1)} ${item[1]}`);
        }
        num %= item[0];
    });
    if (num > 0) {
        res.push(getStr(num));
    }
    return res.join(' ');
};

Explain:

nope.

Complexity: