Plus One in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array of integers, say A. A will hold n elements, and they are non-negative. The whole array A is representing one large number. So if A = [5, 3, 2, 4] is given, it indicates the number 5324. We have to take that array A, then increase the number by 1, and again return the number like an array as given. So after increasing A will be [5, 3, 2, 5]

To solve this, we will follow these steps.

  • Take the array and append each character into a string to make it string
  • then convert the string to an integer, then increase the number by 1
  • then split each digit and make another array

Let us see the following implementation to get a better understanding −

Example (Python)

 Live Demo

class Solution(object):
   def plusOne(self, digits):
      :type digits: List[int]
      :rtype: List[int]
      num = ""
      for i in digits:
         num +=str(i)
      num = int(num)
      num = str(num)
      ans = []
      for i in num:
      return ans
digits = [5,3,2,4]
ob1 = Solution()


digits = [5,3,2,4]


Updated on 28-Apr-2020 16:02:33