題目列表
leetcode 989 號(hào)算法題:數(shù)組形式的整數(shù)加法
leetcode 66 號(hào)算法題:加 1
leetcode 415 號(hào)算法題:字符串相加
leetcode 67 號(hào)算法題:二進(jìn)制求和
leetcode 2 號(hào)算法題:兩數(shù)相加
作者:tangweiqun
鏈接:https://leetcode-cn.com/problems/add-to-array-form-of-integer/solution/jian-dan-yi-dong-javacpythonjs-pei-yang-a8ofe/
leetcode 989 號(hào)算法題:數(shù)組形式的整數(shù)加法
def addTwoNum(self, num1: List[int], num2: List[int]) -> List[int]:
res = []
i1, i2, carry = len(num1) - 1, len(num2) - 1, 0
while i1 >= 0 or i2 >= 0:
x = num1[i1] if i1 >= 0 else 0
y = num2[i2] if i2 >= 0 else 0
sum = x + y + carry
res.append(sum % 10)
carry = sum // 10
i1, i2 = i1 - 1, i2 - 1
if carry != 0: res.append(carry)
return res[::-1]
def addToArrayForm(self, A: List[int], K: int) -> List[int]:
res = []
i, carry = len(A) - 1, 0
while i >= 0 or K != 0:
x = A[i] if i >= 0 else 0
y = K % 10 if K != 0 else 0
sum = x + y + carry
res.append(sum % 10)
carry = sum // 10
i -= 1
K //= 10
if carry != 0: res.append(carry)
return res[::-1]