[leetcode: Python]415. Add Strings

本文介绍了一种解决两个大数相加问题的算法实现,通过字符串操作而非直接转换为整数的方式完成加法运算。提供了两种方法:一种是逐位相加并考虑进位,另一种是将每个字符转换为其数值等价物再进行加法运算。

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

Title
Given two non-negative integers 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.

大数问题
方法一:102ms

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """

        l1 = len(num1)
        l2 = len(num2)
        lm = max(l1, l2)
        num1 = num1.zfill(lm)
        num2 = num2.zfill(lm)
        num1 = num1[::-1]
        num2 = num2[::-1]

        s = []
        c = 0
        for i in range(lm):
            sum1 = int(num1[i]) + int(num2[i]) + c
            c, sum1 =divmod(sum1, 10)
            s.append(str(sum1))
        l = s[::-1]
        s1 = ''.join(l)
        if c == 1:
            s1 = '1' + s1
        if  len(s1) == 1:
            return l[0]
        return s1

方法二:78ms

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        t1 = 0
        for i in num1:
            t1 *= 10
            t1 += ord(i) - 48


        t2 = 0
        for i in num2:
            t2 *= 10
            t2 += ord(i) - 48

        return str(t1 + t2)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值