Go Back

415. Add Strings

Difficulty:
Easy
Related Topics:
  • Math
Leetcode:

Problem

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

/**
 * @param {string} num1
 * @param {string} num2
 * @return {string}
 */
var addStrings = function(num1, num2) {
    var len1 = num1.length;
    var len2 = num2.length;
    var max = Math.max(len1, len2);
    var res = Array(max);
    var carry = 0;
    var 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('');
};

Explain:

nope.

Complexity:

  • Time complexity :
  • Space complexity :