From e909e4c5cbd20795d6cb65c525ace084b6566e87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=8E=E6=B4=AA=E5=AE=87?= Date: Mon, 22 Aug 2022 01:34:16 +0800 Subject: [PATCH] Tony Yan Tony Yan completed exercise 2 --- lib/add.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/add.js b/lib/add.js index 1714b95..542fb18 100644 --- a/lib/add.js +++ b/lib/add.js @@ -1,5 +1,16 @@ -function add() { +function add(a, b) { // 实现该函数 + if (a.length < b.length) [a, b] = [b, a] + b = new Array(a.length - b.length).fill('0').join('') + b + let carry = 0 + let nums = [] + for (let i = a.length - 1; i >= 0; i--) { + let num = carry + parseInt(a[i]) + parseInt(b[i]) + nums.push(num % 10) + carry = parseInt(num / 10) + } + if (carry) nums.push(carry) + return nums.reverse().join('') } module.exports = add \ No newline at end of file