LeetCode #415: Add Strings

本文介绍了一种解决两个大数相加问题的算法实现,输入为两个非负整数字符串形式,输出也为字符串形式。该算法通过从后往前逐位相加的方式,实现了不使用内置大数库或直接转换为整数的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Statement

(Source)Given two non-negative numbers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

Solution

第一遍从后往前扫描的时候先把中间结果(按位求和)存到较长的“数字”里,此时不考虑进位。第二遍从后往前扫描的时候处理进位。时间复杂度与空间复杂度均为: O(max(len(num1),len(num2))) .

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        x = map(int, list(num1))
        y = map(int, list(num2))
        if len(x) > len(y):
            x, y = y, x
        n1, n2 = len(x), len(y)
        i, j = n1 - 1, n2 - 1
        while i >= 0:
            y[j] += x[i]
            i -= 1
            j -= 1
        j = n2 - 1
        while j >= 1:
            if y[j] >= 10:
                y[j - 1] += 1
                y[j] -= 10
            j -= 1

        return ''.join(map(str, y))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值