力扣算法:字符串相加

力扣算法:字符串相加

  • 一、字符串相加
    • 1、问题
    • 2、提示
    • 3、思路
    • 4、代码
    • 5、时间与空间复杂度
  • 备注

一、字符串相加

1、问题

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

示例1:

输入:nums1 = “11” , nums2 = “123”
输出:“134”

示例2:

输入:nums1 = “165” , nums2 = “957”
输出:“1122”

2、提示

  1. num1 和num2 的长度都小于 5100
  2. num1 和num2 都只包含数字 0-9
  3. num1 和num2 都不包含任何前导零
  4. 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式

3、思路

因为本题不能使用任何 BigInteger 库,所以我们可以使用双指针来模拟人工计算,步骤如下:

  1. 创建指针 i 指向 nums1末位数字,j 指向 nums2 末位数字,从后向前遍历。
  2. 用carry来记录进位值初始化为0,由(num1[i]+num2[j]+carry)//10获得。
  3. 相加后的当前位数字由(num1[i]+num2[j]+carry)%10获得。
  4. 若遍历过程中,nums1 或 nums2 当前已无数字,则用 0 补位来计算。

力扣算法:字符串相加_第1张图片

4、代码

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        res = ""
        i, j, carry = len(num1) - 1, len(num2) - 1, 0
        while i >= 0 or j >= 0:
            n1 = int(num1[i]) if i >= 0 else 0
            n2 = int(num2[j]) if j >= 0 else 0
            tmp = n1 + n2 + carry
            carry = tmp // 10
            res = str(tmp % 10) + res
            i, j = i - 1, j - 1
        return "1" + res if carry else res
if __name__ == "__main__":
    solution=Solution()
    print(solution.addStrings(num1 = "165",num2 = "957"))

5、时间与空间复杂度

时间复杂度:O(max⁡(len1,len2))
其中 len1=num1.length,len2=num2.length。竖式加法的次数取决于较大数的位数。

空间复杂度:O(1)
除答案外,只需要常数空间存放若干变量。

备注

转载于:
1、力扣(LeetCode)
https://leetcode-cn.com/problems/add-strings/solution/zi-fu-chuan-xiang-jia-by-leetcode-solution/
2、demigodliu
https://leetcode-cn.com/problems/add-strings/solution/mo-ni-zi-fu-chuan-xiang-jia-by-demigodli-d5j0/

你可能感兴趣的:(力扣算法,算法,字符串,leetcode,python)