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 −

 Live Demo

class Solution(object):
   def addToArrayForm(self, A, K):
      num_A = int(''.join(str(i) for i in A))
      res = list(str(num_A+K))
      res = list(map(int,res))
      return res
ob1 = Solution()
print(ob1.addToArrayForm([5,3,4], 78))

Input

[5,3,4]
78

Output

[6,1,2]

Updated on: 28-Apr-2020

348 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements