Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现大数相加函数 #245

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
19 changes: 17 additions & 2 deletions lib/add.js
Original file line number Diff line number Diff line change
@@ -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