leetcode with python:415. Add Strings

题目:

Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

给定两以字串表示的数字,以字串型态回传两者相加的结果
不可直接将输入转int相加

这题有点像2.,运用的手法也类似
不过那题数字是以linked list表示,这题是以字串表示

class Solution:    def addStrings(self, num1: str, num2: str) -> str:        num1=num1[::-1]        num2=num2[::-1]                if len(num1)>len(num2):            num2=num2+"0"*(len(num1)-len(num2))        else:            num1=num1+"0"*(len(num2)-len(num1))                    ans=""        temp=0            for i in range(len(num1)):            x=int(num1[i])+int(num2[i])+temp            temp=x//10            ans=str(x%10)+ans                    if temp:            ans=str(temp)+ans                    return ans

先将字串反转方便操作
若两字串长度不同,以"0"补足两者的长度差
举例来解释,10+999相当于010+999

开始对每位进行运算(x=int(num1[i])+int(num2[i])+temp)
temp(x//10)代表进位值,而x%10是留在该位数的值
每次的x%10都加到ans字串
相加完记得检查是否有残余的temp,像999+999=1998两三位数相加进位到四位数
结果回传ans
最后执行时间为27ms(faster than 99.69%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章