415. Add Strings

Description

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. 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("");
};

results matching ""

    No results matching ""