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.
/** * @param {string} num1 * @param {string} num2 * @return {string} */ var addStrings = function(num1, num2) { //Make sure num1 is the longer string if(num1.length < num2.length){ var t = num1; num1 = num2; num2 = t; } //Give a leading zero to make sure num1 is longer even if num1 and num2 have same length num1 = ‘0’ + num1; num1 = num1.split("").reverse(); num2 = num2.split("").reverse(); console.log(num1,num2) for(var i=0;i<num1.length;i++){ var n1 = parseInt(num1[i]); var n2 = parseInt((typeof num2[i] == ‘undefined’)?0:num2[i]); var t = n1 + n2; num1[i] = t % 10; if(t >= 10){ num1[i+1] = parseInt(num1[i+1]) + 1; } } if(num1[num1.length-1] == 0){ num1.pop(); } num1 = num1.reverse().join(”); return num1; };