Add Strings
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.
Write your solution:
Test Case 1
Input: "63", "181"
Output: "244"
Test Case 2
Input: "11", "1"
Output: "12"
Test Case 3
Input: "1010", "1011"
Output: "2021"
Solution
function addStrings(num1, num2) {
const len1 = num1.length;
const len2 = num2.length;
const max = Math.max(len1, len2);
const res = Array(max);
let carry = 0;
let val = 0;
for (var i = 0; i < max; i++) {
val = Number(num1[len1 - 1 - i] || 0) + Number(num2[len2 - 1 - i] || 0) + carry;
carry = Math.floor(val / 10);
res[max - 1 - i] = val % 10;
}
return (carry || '') + res.join('');
}