Leetcode: Plus One

Rachit Gupta
1 min readDec 28, 2016

--

  1. Reverse Iterate through the array
  2. As long as there are only 9’s convert them to one
  3. For a non-9 number add 1 and break
  4. Check if the first number is 0, indicating that all the numbers were 9, insert 1 at the beginning for this case

Remarks:

  1. 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

--

--