- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
nums[i] := 0
i := i - 1
if i < 0, then
insert 1 into nums at position 0
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))
[2, 6, 9]
[2, 7, 0]
- Add 1 to a number represented as a linked list?
- Add 1 to a number represented as linked list?
- Program to find sum of digits until it is one digit number in Python
- Program to find super digit of a number in Python
- Python program to find largest number in a list
- Program to count number of elements in a list that contains odd number of digits in Python
- Python Program to remove a specific digit from every element of the list
- Python program to find the largest number in a list
- Python program to find the smallest number in a list
- Program to count number of swaps required to change one list to another in Python?
- Python program to find the second largest number in a list
- Python Program to Search the Number of Times a Particular Number Occurs in a List
- Program to check we can get a digit pair and any number of digit triplets or not in Python
- Program to find minimum cost to reduce a list into one integer in Python
- One of the two digits of a two-digit number is three times the other digit If you interchange the digits of this two-digit number and add the resulting number to the original number, you get $88$. What is the original number?