Add One in Python


Suppose we have a list of integers called n, this is representing a decimal number and n[i] is between [0, 9]. So, if the n is [2, 4, 9] represents the number 249. We have to find the same list in the same representation except modified so that 1 is added to the number.

So, if the input is like n = [9,9], then the output will be [1, 0, 0]

To solve this, we will follow these steps −

  • n := add 0 at the beginning of n

  • increase last element of n by 1

  • for i in range size of n - 1 to 0, decrease by 1, do

    • n[i-1] := n[i-1] + quotient of (n[i] / 10)

    • n[i] := n[i] mod 10

  • return n if n[0] > 0 otherwise n from index 1 to end

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, n):
      n = [0] + n
      n[-1] += 1
      for i in range(len(n) - 1, 0, -1):
         n[i-1] += n[i] // 10
         n[i] = n[i] % 10
      return n if n[0] > 0 else n[1:]
ob = Solution()
print(ob.solve([9,9]))

Input

[9,9]

Output

[1, 0, 0]

Updated on: 02-Sep-2020

557 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements