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 and num2 is < 5100.
- Both num1 and num2 contains only digits 0-9.
- Both num1 and num2 does not contain any leading zero.
- You must not use any built-in BigInteger library or convert the inputs to integer directly.
Solution
var addStrings = function(num1, num2) {
return (parseInt(num1)+parseInt(num2)).toString()
};
const add = (s, t) => {
const w = Math.max(s.length, t.length);
s = s.padStart(w, '0');
t = t.padStart(w, '0');
let c = 0;
let res = '';
for (let i = s.length - 1; i >= 0; i -= 1) {
const current = parseInt(s[i], 10) + parseInt(t[i], 10) + c;
if (i === 0) {
res = current + res;
} else {
const dig = current % 10;
c = Math.floor(current / 10);
res = dig + res;
}
}
return res;
};
comments powered by Disqus