Add to Array-Form of Integer in Python


Suppose we have a number in array form. So if the number is say 534, then it is stored like [5, 3, 4]. We have to add another value k with the array form of the number. So the final number will be another array of digits.

To solve this, we will follow these steps −

  • Take each number and make them string, then concatenate the string
  • convert the string into integer, then add the number
  • Then convert it into string again, and make an array by taking each digit form the string.

Example

Let us see the following implementation to get better understanding −

class Solution(object):
   def addToArrayForm(self, A, K):
      """
      :type A: List[int]
      :type K: int
      :rtype: List[int]
      """
      num_A = int(''.join(str(i) for i in A))
      res = list(str(num_A+K))
      res = list(map(int,res))
      return res

Input

[5,3,4]
78

Output

[6,1,2]
raja
Published on 16-Jan-2020 11:50:21
Advertisements