题解 | #高精度整数加法#
高精度整数加法
https://www.nowcoder.com/practice/49e772ab08994a96980f9618892e55b6
const rl = require("readline").createInterface({ input: process.stdin }); var iter = rl[Symbol.asyncIterator](); const readline = async () => (await iter.next()).value; void (async function () { // Write your code here /** * 解题步骤 * 1.先将两个字符串用split方法,转换出数组 * 2.判断两个字符串数组的长度和暂存数temp * 3.使用~~first.pop()的目的,保证若前者长度小于后者长度,此时first.pop()=undefined,而~~undefined=0 * 4.然后将同一位置的数字进行相加,若大于两者之和大于9,则需要进位,即将temp的值变为1,也就是true */ let lineArr = []; while ((line = await readline())) { lineArr.push(line); } let first = lineArr[0].split(""); let second = lineArr[1].split(""); let temp = 0; // 暂存数 let result = ""; while (first.length || second.length || temp) { temp += ~~first.pop() + ~~second.pop(); // 此处temp为Number类型 result = (temp % 10) + result; // 此处result为String类型 temp = temp > 9 ? 1 : 0; // 判断是否需要进位 } console.log(result); })();