The task is taken from leetcode
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.
My solution 1
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var addStrings = function(num1, num2) {
let result = '';
let carry = 0;
const LEN1 = num1.length - 1;
const LEN2 = num2.length - 1;
for (let i = 0, L = Math.max(LEN1, LEN2); i <= L; i++ ) {
const numb1 = num1[LEN1 - i] ? num1[LEN1 - i] | 0 : 0;
const numb2 = num2[LEN2 - i] ? num2[LEN2 - i] | 0 : 0;
const tmp = numb1 + numb2 + carry;
carry = tmp > 9 ? 1 : 0;
result = `${tmp % 10}${result}`;
}
return carry > 0 ? 1 + result : result;
};
My solution 2
/**
* @param {string} num1
* @param {string} num2
* @return {string}
*/
var addStrings = function(num1, num2) {
let result = '';
let carry = i = 0;
const LEN1 = num1.length - 1;
const LEN2 = num2.length - 1;
while(num1[LEN1 - i] || num2[LEN2 - i]) {
const numb1 = num1[LEN1 - i] ? num1[LEN1 - i] | 0 : 0;
const numb2 = num2[LEN2 - i] ? num2[LEN2 - i] | 0 : 0;
const tmp = numb1 + numb2 + carry;
carry = tmp > 9;
result = tmp % 10 + result;
i++;
}
return carry > 0 ? 1 + result : result;
};