Skip to content

Commit 36cfc68

Browse files
committed
Add solution #415
1 parent 44cfc8e commit 36cfc68

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@
185185
405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy|
186186
412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy|
187187
414|[Third Maximum Number](./0414-third-maximum-number.js)|Easy|
188+
415|[Add Strings](./0415-add-strings.js)|Easy|
188189
419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium|
189190
435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium|
190191
442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium|

solutions/0415-add-strings.js

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 415. Add Strings
3+
* https://leetcode.com/problems/add-strings/
4+
* Difficulty: Easy
5+
*
6+
* Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and
7+
* num2 as a string.
8+
*
9+
* You must solve the problem without using any built-in library for handling large integers (such
10+
* as BigInteger). You must also not convert the inputs to integers directly.
11+
*/
12+
13+
/**
14+
* @param {string} num1
15+
* @param {string} num2
16+
* @return {string}
17+
*/
18+
var addStrings = function(num1, num2) {
19+
let result = '';
20+
21+
for (let i = num1.length - 1, j = num2.length - 1, carry = 0; i > -1 || j > -1 || carry === 1;) {
22+
if (i > -1) {
23+
carry += num1.charCodeAt(i--) - 48;
24+
}
25+
if (j > -1) {
26+
carry += num2.charCodeAt(j--) - 48;
27+
}
28+
result = (carry % 10) + result;
29+
carry = Math.floor(carry / 10);
30+
}
31+
32+
return result;
33+
};

0 commit comments

Comments
 (0)