131 - 415 字符串相加

题目

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

注意:

  1. num1 和num2 的长度都小于 5100.

  2. num1 和num2 都只包含数字 0-9.

  3. num1 和num2 都不包含任何前导零。

  4. 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。

解答

不能转成整数,因此要模拟加法。。所以还是要每位数转成数字。。

https://leetcode-cn.com/problems/add-strings/solution/add-strings-shuang-zhi-zhen-fa-by-jyd/

感觉不应该用字符串,每次增加都会新建一个字符串,感觉很浪费内存。

不如每次都塞进数组里面,最后排序并变成字符串输出比较好。

var addStrings = function(num1, num2) {
  let res = [],
    i = num1.length - 1,
    j = num2.length - 1,
    carry = 0
  while (i >= 0 || j >= 0) {
    const n1 = i < 0 ? 0 : parseInt(num1[i])
    const n2 = j < 0 ? 0 : parseInt(num2[j])
    const temp = n1 + n2 + carry
    carry = ~~(temp / 10)
    res.push(temp % 10)
    i--
    j--
  }
  if (carry) {
    res.push(carry)
  }
  return res.reverse().join("")
};

Runtime: 64 ms, faster than 79.98% of JavaScript online submissions for Add Strings.

Memory Usage: 36.4 MB, less than 37.50% of JavaScript online submissions for Add Strings.

Runtime: 52 ms, faster than 60.04% of Python3 online submissions for Add Strings.

Memory Usage: 13.7 MB, less than 5.55% of Python3 online submissions for Add Strings.

Runtime: 40 ms, faster than 92.18% of Python3 online submissions for Add Strings.

Memory Usage: 13.9 MB, less than 5.55% of Python3 online submissions for Add Strings.

好吧。。只是运行速度快了一点,并没有减少多少内存

Runtime: 4 ms, faster than 53.77% of Go online submissions for Add Strings.

Memory Usage: 6.8 MB, less than 60.00% of Go online submissions for Add Strings.

Last updated

Was this helpful?