415. Add Strings
Description
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Solution
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var addStrings = function(num1, num2) {
"use strict";
let result = "";
let carry = 0;
for (let i = num1.length-1, j = num2.length-1; i >= 0 || j >= 0; i--, j--) {
let a = num1[i] || 0;
let b = num2[j] || 0;
let digitSum = parseInt(a) + parseInt(b) + carry;
carry = (digitSum.toString().length === 2) ? 1 : 0;
result += (digitSum % 10).toString();
}
if (carry) {
result += carry;
}
return result.split("").reverse().join("");
};