Skip to content

Commit 63a956c

Browse files
author
zongyanqi
committed
add Easy_415_Add_Strings
1 parent fa2edc3 commit 63a956c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Easy_415_Add_Strings.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
3+
* Note:
4+
*
5+
* The length of both num1 and num2 is < 5100.
6+
* Both num1 and num2 contains only digits 0-9.
7+
* Both num1 and num2 does not contain any leading zero.
8+
* You must not use any built-in BigInteger library or convert the inputs to integer directly.
9+
*/
10+
11+
/**
12+
* @param {string} num1
13+
* @param {string} num2
14+
* @return {string}
15+
*/
16+
var addStrings = function (num1, num2) {
17+
var carry = 0;
18+
var len1 = num1.length;
19+
var len2 = num2.length;
20+
var forCount = Math.max(len1, len2);
21+
var newNum = '';
22+
for (var i = 0; i < forCount; i++) {
23+
var a = parseInt(num1[len1 - 1 - i]) || 0;
24+
var b = parseInt(num2[len2 - 1 - i]) || 0;
25+
var c = a + b + carry;
26+
carry = Math.floor(c / 10);
27+
var e = c % 10;
28+
newNum = e + newNum;
29+
}
30+
31+
if (carry) {
32+
newNum = carry + newNum
33+
}
34+
return newNum;
35+
};
36+
37+
console.log(addStrings('12', '123') == '135');

0 commit comments

Comments
 (0)