最近疫情在家办公,足不出户,做做 PAT 的题。奉上【PAT甲级】JS 解题分析————第四篇。
原题
Given a non-negative integer N, your task is to compute the sum of all the digits of N, and output every digit of the sum in English.
Input Specification:
Each input file contains one test case. Each case occupies one line which contains an N (≤10^100).
Output Specification:
For each test case, output in one line the digits of the sum in English words. There must be one space between two consecutive words, but no extra space at the end of a line.
Sample Input:
12345
Sample Output:
one five
原题翻译
一个非负整数 N,你的任务时计算 N 的所有数字之和,用英文输出
输入格式:每个测试用例占一行,包含一个 N (≤10^100)。
输出格式:对于每个测试用例,使用英文单词输出数字之和,单词之间用空格连接。
解题
思路:
定义 0-9 数字与英文单词的映射关系,计算 N 的所有数字之和。把 sum 转换成 string 分割得到数字,将数字转换成英文单词输出。
注意事项:
- 0-9 数字的英文单词一定要拼写正确。
测试用例:
- input: 12345 output: one five
- input: 999113; output: three two
- input: 0; output: zero
代码:
const readline = require('readline');
rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// 单行输入
rl.on('line', function(input) {
// 获取入参
const arg = input.trim().split(' ');
// 处理逻辑
const ret = deal(arg);
// 输出结果
console.log(ret);
})
/**
* 处理逻辑
* @param {array} 入参集合
* @returns {string} 返回值
*/
function deal(arg) {
const map = {
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
0: 'zero'
};
const sum = arg[0].split('').map(i => i*1).reduce((s, i) => s+i, 0);
const tmp = String(sum).split('');
const ret = tmp.map(i => map[i])
return ret.join(' ');
}
(以上代码,是在下能想到的一种解法,期待评论区有更多大神分享更优的解法)