From d9d22a85e09288364a9d63fbe7d7c1fc2d71819d Mon Sep 17 00:00:00 2001 From: goose Date: Sat, 20 Aug 2022 23:22:16 +0800 Subject: [PATCH] feat(add): big number add; --- lib/add.js | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/lib/add.js b/lib/add.js index 1714b95..bd5d924 100644 --- a/lib/add.js +++ b/lib/add.js @@ -1,5 +1,27 @@ -function add() { +function add(num1, num2) { // 实现该函数 + let maxLength = Math.max(num1.length, num2.length); + // num1和num2位数对齐,位数较小的前面补0 + num1 = num1.padStart(maxLength, '0'); + num2 = num2.padStart(maxLength, '0'); + let res = '';// 存放最后得到的结果 + let figure = 0;// figure = 两个数字对应位数数值相加 + 进位 + let currentNum = 0;// 对应位数的结果 + let carry = 0;// 进位 + for (let i = num1.length - 1; i >= 0; i--) { + figure = parseInt(num1[i]) + parseInt(num2[i]) + carry; + currentNum = figure % 10; + carry = Math.floor(figure / 10); + + res = currentNum + res; + } + // 首位进位 + if (carry) { + res = carry + res + } + console.log(res); + return res } + module.exports = add \ No newline at end of file