File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 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' ) ;
You can’t perform that action at this time.
0 commit comments