day1-989-数组形式的整数加法

题目列表

leetcode 989 号算法题:数组形式的整数加法
leetcode 66 号算法题:加 1
leetcode 415 号算法题:字符串相加
leetcode 67 号算法题:二进制求和
leetcode 2 号算法题:两数相加
作者:tangweiqun
链接:https://leetcode-cn.com/problems/add-to-array-form-of-integer/solution/jian-dan-yi-dong-javacpythonjs-pei-yang-a8ofe/

leetcode 989 号算法题:数组形式的整数加法

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]

你可能感兴趣的:(day1-989-数组形式的整数加法)