题解 | #高精度整数加法#
高精度整数加法
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; let lines = []; void (async function () { // Write your code here while ((line = await readline())) { lines.push(line); if (lines.length === 2) { getResult(lines); } } })(); function getResult(lines) { let short = lines[0].split("").map(Number); let long = lines[1].split("").map(Number); if (short.length > long.length) { let temp = short; short = long; long = temp; } short.unshift(...new Array(long.length - short.length).fill(Number(0))); // console.log(short) let result = []; let c = 0; while (long.length) { let r = long.pop() + short.pop() + c; result.unshift(r % 10); c = parseInt(r / 10); if (long.length === 0) { result.unshift(c); break; } } while (result[0] === 0) { result.shift(); } if(result.length===0){ result=[0] } console.log(result.join("")); }
思路就是:将两个字符串转成数值,短的那段前边补足0至和长字符长度相等。然后按照加法运算法则将结果计入数组,最后将数组前空余的0去掉