Leetcode: Plus One
1 min readDec 28, 2016
- Reverse Iterate through the array
- As long as there are only 9’s convert them to one
- For a non-9 number add 1 and break
- Check if the first number is 0, indicating that all the numbers were 9, insert 1 at the beginning for this case
Remarks:
- O(n) time, O(1) space
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
for i in range(len(digits) - 1, -1, -1):
if digits[i] == 9:
digits[i] = 0
else:
digits[i] += 1
break
if digits[0] == 0: digits.insert(0, 1)
return digits