From cb0e930baa9cddd9b9c44aa38c92addbf61c2ab8 Mon Sep 17 00:00:00 2001 From: zoey Date: Sat, 20 Aug 2022 16:16:36 +0800 Subject: [PATCH] exercise2 --- lib/add.js | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/add.js b/lib/add.js index 1714b95..e24532a 100644 --- a/lib/add.js +++ b/lib/add.js @@ -1,5 +1,16 @@ -function add() { +function add(num1, num2) { // 实现该函数 + let res = '' + let i = num1.length - 1, j = num2.length - 1, flag = 0 + while (i >= 0 || j >= 0 || flag !== 0) { + if (i >= 0) flag += num1.charCodeAt(i--) - 48 + if (j >= 0) flag += num2.charCodeAt(j--) - 48 + res = '' + flag % 10 + res + flag /= 10 + // 向下取整 + flag = ~~flag + } + return res } module.exports = add \ No newline at end of file