From 5aa28cc827187db0aaeb0936c22e36c9ed37c7da Mon Sep 17 00:00:00 2001 From: yurui wu Date: Sun, 21 Aug 2022 19:44:45 +0800 Subject: [PATCH] =?UTF-8?q?dev|execise2=E4=BD=9C=E4=B8=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/add.js | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/lib/add.js b/lib/add.js index 1714b95..67ef911 100644 --- a/lib/add.js +++ b/lib/add.js @@ -1,5 +1,35 @@ -function add() { - // 实现该函数 +function add(strOne, strTwo) { + // 比较两个数长度 短的一方前面补0 + if (strOne.length > strTwo.length) { + let arr = Array(strOne.length - strTwo.length).fill(0); + strTwo = arr.join('') + strTwo + } else if (strOne.length < strTwo.length) { + let arr = Array(strTwo.length - strOne.length).fill(0); + strOne = arr.join('') + strOne + } + // 字符串转为数组后反转,方便对数组加法运算 + var strOneArr = strOne.split('').reverse() + var strTwoArr = strTwo.split('').reverse() + var sign = 0 // 进位标识 + var resultArr = [] + + for (let i = 0; i < strOneArr.length; i++) { + var addResult = Number(strOneArr[i]) + Number(strTwoArr[i]) + sign + if (addResult >= 10) { + sign = 1 + resultArr.push(addResult % 10) + continue + } else { + sign = 0 + resultArr.push(addResult) + continue + } + } + // 最后一位计算完后,有进位,计入进位 + if (sign) { + resultArr.push(sign) + } + return resultArr.reverse().join('') } module.exports = add \ No newline at end of file