題目:
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%)
那我們下題見