Add to Array-Form of Integer in Python

PythonServer Side ProgrammingProgramming

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.


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))




Published on 16-Jan-2020 11:50:21