[路飞]_每天刷leetcode_70(字符串相加 Add strings)

145 阅读2分钟

「这是我参与2022首次更文挑战的第31天,活动详情查看:2022首次更文挑战

字符串相加 Add strings

LeetCode传送门415. 字符串相加

题目

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和并同样以字符串形式返回。

你不能使用任何內建的用于处理大整数的库(比如 BigInteger), 也不能直接将输入的字符串转换为整数形式。

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

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

Example:

Input: num1 = "11", num2 = "123"
Output: "134"

Input: num1 = "456", num2 = "77"
Output: "533"

Input: num1 = "0", num2 = "0"
Output: "0"

Constraints:

  • 1<=num1.length,num2.length<=1041 <= num1.length, num2.length <= 10^4
  • num1 and num2 consist of only digits.
  • num1 and num2 don't have any leading zeros except for the zero itself.

思考线


解题思路

我们先让字符串转换成数组并把数组的值都转换为Number类型,便于后面计算。

这道题我们可以想想成我们小时候做加法计算的列竖式的形式。

在列竖式计算方法中,我们先计算位数比较小的值,如果计算结果大于9,我们向前进1,并把此次计算结果的个数为放到最后结果的个数位上,依次类推,得到结果。 现在我们要用数组模拟这样一个过程:

我们从数组的尾部进行相加操作,把进位放到carry这个变量中。把结果放到res数组中。

在这里我们如果任一数组长度为0,我们只需要考虑把另一个数组和carry的值即可。

最后我们把结果数组转换为字符串返回,即是我们想要的结果。

代码如下:

function addStrings(num1: string, num2: string): string {
    const arr1 = num1.split('').map(s => Number(s))
    const arr2 = num2.split('').map(s => Number(s))
    const res = [];
    let carry = 0;
    function getAdd(n) {
        carry = Math.floor(n / 10)
        res.unshift(n % 10)
    }
    while (arr1.length && arr2.length) {
        const n1 = arr1.pop()
        const n2 = arr2.pop()
        getAdd(n1 + n2 + carry)
    }
    while (arr1.length) {
        getAdd(arr1.pop() + carry)
    }
    while (arr2.length) {
        getAdd(arr2.pop() + carry)
    }
    if (carry) res.unshift(carry)
    return res.join('')
};

时间复杂度

O(m+n): m为num1的长度,n为num2的长度

这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。