【PAT甲级】1001 A+B Format (JS)

最近疫情在家办公,足不出户,想着做做 PAT 的题。

PAT 在线练习不像 LeetCode 那么完善,没有给出解题模板(函数外壳),提交如果未通过(答案错误),不会该条测试的输入,只能自查代码逻辑是否存在遗漏的点,或者搜索该题其他文章中提到的注意事项,着实有点费劲 😭。

最近做题发现,PAT甲级网上的文章基本都是 C/C++ 的解题代码,很少看到使用 JavaScript 的,于是决定将解题思路及代码用文章记录下来,与其他刷题的前端小伙伴们分享、交流。

原题

Calculate a+b and output the sum in standard format – that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

Input Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where −106≤a,b≤106. The numbers are separated by a space.

Output Specification:

For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

Sample Input:

-1000000 9

Sample Output:

-999,991

原题翻译

计算a+b并以标准格式输出,即:每三位加一个 “,” 的格式输出(若少于四个数字则直接输出)。

输入格式:每个输入文件包含一个测试用例。每个用例包含一对整数a和b,其中(-10^6 ≤ a,b ≤ 10^6),数字之间用空格分割。

输出格式:对于每个测试用例,你需要按照格式要求在一行中输出a+b的计算结果。

解题

思路:

对a+b的和, 进行除 1000 的迭代处理,每次迭代的余数放入数组中,最后用逗号连接即可。

注意事项:

  1. a+b的和可能为正数,也可能为负数。
  2. 从后往前每三位添加逗号,四位以内(-999~999)无需处理。

测试用例:

  • input:-1000000 9; output -999,991
  • input: 1000 1; output: 1,001
  • input: -999 0; output: -999

代码:

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 [a, b] = arg;
  let s = Number(a) + Number(b);
  const arr = [];
  while(s > 999 || s < -999) {
    // 取余结果带符号,需取绝对值;补零 (如 s = 1001, 此处的 tmp 为 001)
    let tmp = '00' +  Math.abs(s % 1000);
    tmp = tmp.slice(-3)
    arr.unshift(tmp);
    s = s / 1000;
    // 非负数向下取整;负数向上取整
    s = s >=0 ? Math.floor(s) : Math.ceil(s);
  }
  arr.unshift(s);
  return arr.join(',')
}

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

PAT 考试练习,JavaScript(node) 在线答题,需使用 node 的 readline 逐行读取 input, 通过 console.log 打印 output。单行输入和多行输入的处理方式不同,上述代码给出了单行输入的处理方式。多行输入处理,参考 https://www.cnblogs.com/floor/p/6667059.html 。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值