【较难】算法nodeJs:学英语

4 阅读2分钟

描述

你需要编写一个程序,使得对于输入的整数,输出其对应的英文单词。

具体地,规则如下:
1.​三位数字看成一整体,每三位数后添加一个计数单位,从小到大依次为 thousand(千)、million(百万);
2.​对于百万以下、千以上的数字,通用公式为 x thousand y ,其中 x 和 y 代表数字;
3.​对于百万以上的数字,通用公式为 x million y thousand z ,其中 x 、y 和 z 代表数字;
4.​每三位数内部,十位和个位之间,需要添加 and ;特别地,若百位为 0 ,则不添加。例如,1234 的英文为 one thousand two hundred and thirty four ,1034 的英文为 one thousand thirty four 。

让我们再来看几个例子:
∙22:twenty two ;
∙100:one hundred ;
∙145:one hundred and forty five ;
∙1234:one thousand two hundred and thirty four ;
∙8088:eight thousand eighty eight ;
∙486669:four hundred and eighty six thousand six hundred and sixty nine ;
∙1652510:one million six hundred and fifty two thousand five hundred and ten 。

输入描述:

在一行上输入一个整数 n(1≦n≦2×106) 代表待转换的整数。

输出描述:

输出若干个小写的英文单词,代表转换后的结果。

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void (async function () {
    const first = [
        "",
        "one",
        "two",
        "three",
        "four",
        "five",
        "six",
        "seven",
        "eight",
        "nine",
        "ten",
        "eleven",
        "twelve",
        "thirteen",
        "fourteen",
        "fifteen",
        "sixteen",
        "seventeen",
        "eighteen",
        "nineteen",
    ];
    const second = [
        "",
        "ten",
        "twenty",
        "thirty",
        "forty",
        "fifty",
        "sixty",
        "seventy",
        "eighty",
        "ninety",
    ];
    const third = ["", " thousand ", " million "];
    let num = parseInt(await readline()); //输入1652510
    let res = "";
    // 转换函数,封装是为了递归调用
    const transfer = (num) => {
        if (num < 20) return first[num];
        if (num < 100)
            return num % 10 === 0
                ? second[Math.floor(num / 10)]
                : second[Math.floor(num / 10)] + " " + first[num % 10];
        if (num % 100 === 0) return first[Math.floor(num / 100)] + " hundred";
        return (
            first[Math.floor(num / 100)] + " hundred and " + transfer(num % 100)
        );
    };
    for (let i = 0; i < 3; i++) {
        if (num === 0) break;
        let cur = num % 1000; //取低三位
        num = Math.floor(num / 1000);
        if (cur) res = transfer(cur) + third[i] + res;
    }
    console.log(res);
})();