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

1962

被折叠的 条评论
为什么被折叠?



