【刷题打卡】415. 字符串相加

159 阅读1分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

一、题目描述:

415. 字符串相加

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

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

示例 1:

输入:num1 = "11", num2 = "123"
输出:"134"

示例 2:

输入:num1 = "456", num2 = "77"
输出:"533"

示例 3:

输入:num1 = "0", num2 = "0"
输出:"0"

提示:

  • 1 <= num1.length, num2.length <= 10^4
  • num1 和num2 都只包含数字 0-9
  • num1 和num2 都不包含任何前导零

二、思路分析:

看似简单实际不然的题

  • 把两个num串长度对齐
  • 设置进位变量,控制进位的,所以加的时候,是连着进位一起加进去
  • 每次循环都需要调整进位,我一开始忘了把他调回0
  • 记得最后一位数有可能是来自于进位
  • 返回的字符串是得到的字符串的反串,反串比较好处理

三、AC 代码:

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        if len(num1) < len(num2): num2, num1 = num1, num2
        num2 = "0" * (len(num1) - len(num2)) + num2

        p, increase, res = len(num1) - 1, 0, ""
        while p >= 0:
            n1, n2 = int(num1[p]), int(num2[p])
            res += str((n1 + n2 + increase) % 10)
            if (n1 + n2 + increase) // 10 > 0:
                increase = 1
            else:
                increase = 0
            p -= 1
        if increase > 0: res += str(increase)
        return res[::-1]

范文参考:

字符串相加 (双指针,清晰图解) - 字符串相加 - 力扣(LeetCode) (leetcode-cn.com)