File tree 1 file changed +9
-10
lines changed
1 file changed +9
-10
lines changed Original file line number Diff line number Diff line change 11
11
* @return {string}
12
12
*/
13
13
var addStrings = function (num1 , num2 ) {
14
- let carry = 0 ;
15
14
let sum = ' ' ;
16
-
17
- for (let i = num1 .length - 1 , j = num2 .length - 1 ; i >= 0 || j >= 0 || carry > 0 ; i-- , j-- ) {
18
- const digit1 = i < 0 ? 0 : num1 .charAt (i) - ' 0' ;
19
- const digit2 = j < 0 ? 0 : num2 .charAt (j) - ' 0' ;
20
- const digitsSum = digit1 + digit2 + carry;
21
- sum = ` ${ digitsSum % 10 }${ sum} ` ;
22
- carry = Math .floor (digitsSum / 10 );
15
+ let carry = 0 ;
16
+ for (let i = num1 .length - 1 , j = num2 .length - 1 ; i >= 0 || j >= 0 || carry > 0 ; i-- , j-- ) {
17
+ let digit1 = i < 0 ? 0 : num1 .charAt (i) - ' 0' ;
18
+ let digit2 = j < 0 ? 0 : num2 .charAt (j) - ' 0' ;
19
+ let currSum = digit1 + digit2 + carry;
20
+ // currSum % 10 cannot be currSum - 10, because the first digit may not larger than 10, then cause negative number
21
+ sum = ` ${ currSum % 10 }${ sum} ` ;
22
+ carry = Math .floor (currSum / 10 );
23
23
}
24
-
25
- return sum;
24
+ return sum
26
25
};
27
26
```
You can’t perform that action at this time.
0 commit comments