Program to add one to a number that is shown as a digit list in Python



Suppose we have an array called nums, containing decimal digits of a number. For example, [2, 5, 6] is for 256. We have to add 1 with this number and return the list in same format as before.

So, if the input is like nums = [2, 6, 9], then the output will be [2, 7, 0].

To solve this, we will follow these steps −

  • i := size of nums - 1

  • while i >= 0, do

    • if nums[i] + 1 <= 9, then

      • nums[i] := nums[i] + 1

      • come out from loop

    • otherwise,

      • nums[i] := 0

      • i := i - 1

  • if i < 0, then

    • insert 1 into nums at position 0

  • return nums

Example

Let us see the following implementation to get better understanding

def solve(nums):
   i = len(nums) - 1
   while i >= 0:
      if nums[i] + 1 <= 9:
         nums[i] = nums[i] + 1
         break
      else:
         nums[i] = 0
      i -= 1
   if i < 0:
      nums.insert(0, 1)
   return nums

nums = [2, 6, 9]
print(solve(nums))

Input

[2, 6, 9]

Output

[2, 7, 0]

Advertisements