[
math
]
Leetcode 0066. Plus One
https://leetcode.com/problems/plus-one
How we can add 1 to given number? We need to find the biggest number of 9 in the end of our number, for example for number 5123521999235123999, there will be three 9 in the end. 5123521999235123999 + 1 = 5123521999235124000: so we need to increase previous symbol by one and change all 9 after to 0. Now, the steps of algorithm are to following:
- Let us add one
0before our data to handle cases like9,99,999, … - Find maximum number of
9, starting from the end and moving to the left. - Change all found
9in the end to0and previous digit increasy by1. - Handle border cases: if we have leading zero, remove it.
Complexity time complexity is O(n), where n is length of list. Additional space complexity is O(1), because we edit input data directly.
class Solution:
def plusOne(self, digits):
digits = [0] + digits
end = len(digits) - 1
while digits[end] == 9:
end -= 1
digits[end] += 1
digits[end+1:] = [0] * (len(digits)-1-end)
return digits if digits[0] != 0 else digits[1:]
If you like the solution, you can upvote it on leetcode discussion section: Problem 0066