Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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] represents 256. We have to add 1 to this number and return the list in the same format as before.
So, if the input is like nums = [2, 6, 9], then the output will be [2, 7, 0] (269 + 1 = 270).
Algorithm Steps
To solve this, we will follow these steps −
i := size of nums - 1
-
while i >= 0, do
-
if nums[i] + 1
nums[i] := nums[i] + 1
come out from loop
-
otherwise,
nums[i] := 0
i := i - 1
-
-
if i
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))
The output of the above code is ?
[2, 7, 0]
How It Works
The algorithm starts from the rightmost digit and adds 1. If the digit becomes greater than 9, it sets the digit to 0 and carries over to the next position. This process continues until we find a digit that doesn't overflow or we reach the beginning of the array.
Edge Case Example
Let's see what happens when all digits are 9 ?
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 = [9, 9, 9]
print(solve(nums))
The output of the above code is ?
[1, 0, 0, 0]
Conclusion
This algorithm efficiently handles digit addition with carry-over by processing digits from right to left. It correctly handles all cases including when all digits are 9, requiring an additional digit at the front.
