From 1e8bfda86de4197604ee0bb4b5b8143454e7d1b3 Mon Sep 17 00:00:00 2001 From: songxiulin Date: Tue, 16 Aug 2022 22:35:54 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E5=A4=A7=E6=95=B0=E7=9B=B8?= =?UTF-8?q?=E5=8A=A0=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/add.js | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/add.js b/lib/add.js index 1714b95..bb252ac 100644 --- a/lib/add.js +++ b/lib/add.js @@ -1,5 +1,20 @@ -function add() { - // 实现该函数 +// 实现大数相加 +function add(num1, num2) { + const num1Arr = num1.split('').reverse(); + const num2Arr = num2.split('').reverse(); + const result = []; + let carry = 0; + let len = Math.max(num1Arr.length, num2Arr.length); + for (let i = 0; i < len; i++) { + const sum = Number(num1Arr[i]) + Number(num2Arr[i]) + carry; + carry = Math.floor(sum / 10); + result.push(sum % 10); + } + if (carry) { + result.push(carry); + } + return result.reverse().join(''); + } module.exports = add \ No newline at end of file