Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2e98399

Browse files
Add Strings
1 parent 3bb5392 commit 2e98399

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

‎0415_addStrings.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @param {string} num1 First number to be added, represented as string.
3+
* @param {string} num2 Second number to be added, represented as string.
4+
* @return {string} String representing sum of num1 and num2.
5+
* @summary Add Strings {@link https://leetcode.com/problems/add-strings/}
6+
* @description Given two numbers represented as strings, return sum of them. No built-in library for handling big numbers allowed.
7+
* Space O(n) - Where n is Math.max(num1.length, num2.length).
8+
* Time O(n) - Where n is Math.max(num1.length, num2.length).
9+
*/
10+
const addStrings = (num1, num2) => {
11+
const answer = [];
12+
13+
let carryOver = 0;
14+
let index1 = num1.length - 1;
15+
let index2 = num2.length - 1;
16+
17+
while (index1 >= 0 || index2 >= 0) {
18+
const n1 = index1 >= 0 ? +num1[index1] : 0;
19+
const n2 = index2 >= 0 ? +num2[index2] : 0;
20+
21+
const sum = n1 + n2 + carryOver;
22+
23+
carryOver = sum > 9 ? 1 : 0;
24+
answer.unshift(sum % 10);
25+
26+
index1--;
27+
index2--;
28+
}
29+
30+
if (carryOver) answer.unshift(1);
31+
32+
return answer.join('');
33+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /