【leetcode】415 Add Strings

本文介绍了一个使用Python实现的字符串加法方法。通过定义一个名为Solution的类及其成员函数addStrings来实现两个字符串形式的大整数相加。该方法首先确定两个输入字符串的长度,并根据较短的字符串进行迭代,逐位计算数值之和并处理进位情况。

Python代码,调了几次才AC,有点乱

class Solution(object):
    def addStrings(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        len1 = len(num1)
        len2 = len(num2)
        maxnum = max(len1,len2)
        minnum = min(len1,len2)


        count=0

        res = [0] * (maxnum+1)  
        print(res)  
        for i in range(0,min(len(num1),len(num2))):
            if int(num1[len1-i-1])+int(num2[len2-i-1])+count>=10:

                temp = int(num1[len1-i-1])+int(num2[len2-i-1])+count-10
                count=1
                res[i]=temp

            else:
                temp =  int(num1[len1-i-1])+int(num2[len2-i-1])+count
                res[i]=temp
                count=0
                #print(temp)
        if len1==len2 and count==1:
            res[len1]=count
        for i in range(minnum,maxnum):


            if len1>len2:
                if count+int(num1[len1-i-1])>=10:
                    temp = count+int(num1[len1-i-1])-10

                    res[i]=temp
                    count=1
                else:
                    temp = count+int(num1[len1-i-1])

                    res[i]=temp
                    count=0
            elif len1<len2:     
                if count+int(num2[len2-i-1])>=10:
                    temp = count+int(num2[len2-i-1])-10

                    res[i]=temp
                    count=1
                else:
                    temp = count+int(num2[len2-i-1])

                    res[i]=temp
                    count=0
        if count==1:
            res[maxnum]=1
        res.reverse()        




        self=''

        if res[0]==0:
            flag=1
            res=res[1:len(res)]


        for i in range(0,len(res)):
            res[i]=str(res[i])

        self=self.join(res)
        return self
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值