989. Integer addition of array form

Leetcode-cn.com/problems/ad…

Topic describes

For the non-negative integer X, the array form of X is an array of each digit in left-to-right order. For example, if X = 1231, the array is of the form [1,2,3,1]. Given the array form A of the non-negative integer X, return the array form of the integer X+K. Example 1: input: A = [1,2,0,0], K = 34 output: [1,2,3,4] description: 1200 + 34 = 1234 example 2: input: A = [2,7,4], K = 181 output: [4,5,5] description: 274 + 181 = 455 example 3: input: A = [2,1,5], K = 806 output: [1,0,2,1] description: 215 + 806 = 1021 example 4: input: A = [9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9], K = 1 1 <= a.length <= 10000 0 <= A[I] <= 9 0 <= K <= 10000 if A.length > 1 then A[0]! = 0Copy the code

Train of thought

Formed by converting a string to an int

The key point

code

  • Language support: Python3

Python3 Code:


class Solution:
    def addToArrayForm(self, num: List[int], k: int) - >List[int] :
        # String to int conversion
        resStr = ""
        for i in num:
            resStr +=str(i)
        res = str(int(resStr)+k)
        reslist = []
        for i in res:
            reslist.append(int(i))
        return reslist

if __name__ == '__main__':
    A = [1.2.0.0]
    K = 34
    ret = Solution().addToArrayForm(A, K)
    print(ret)

Copy the code

Complexity analysis

Let n be the length of the array.

  • Time complexity: O(n)O(n)O(n)
  • Space complexity: O(n)O(n)O(n)