Plus One in Python


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+=1
      num = str(num)
      ans = []
      for i in num:
         ans.append(int(i))
      return ans
digits = [5,3,2,4]
ob1 = Solution()
print(ob1.plusOne(digits))

Input

digits = [5,3,2,4]

Output

[5,3,2,5]

Updated on: 28-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements