【PAT甲级】1005 Spell It Right (20 分) JS

这篇博客介绍了如何在JavaScript中解决PAT甲级编程题,涉及将非负整数的各位数字求和,并将和转换成英文单词输出。文章提供了一种解题思路和代码实现,包括数字到英文单词的映射,并给出了测试用例及其输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近疫情在家办公,足不出户,做做 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 分割得到数字,将数字转换成英文单词输出。

注意事项:

  1. 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(' ');
}

(以上代码,是在下能想到的一种解法,期待评论区有更多大神分享更优的解法)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值