Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions lib/add.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
function add() {
// 实现该函数
function add(a, b) {
const maxLength = Math.max(a.length, b.length);
const num1 = a.padStart(maxLength, '0');
const num2 = b.padStart(maxLength, '0');
let res = '';
let carry = 0;
for (let i = num1.length - 1; i >= 0; --i) {
const count = parseInt(num1[i]) + parseInt(num2[i]) + carry;
carry = Math.floor(count / 10);
res = count % 10 + res;
}
if (carry) {
res = '1' + res;
}
return res;
}

module.exports = add