Skip to content

Instantly share code, notes, and snippets.

@wanderindev
Last active July 9, 2022 20:07
Show Gist options
  • Save wanderindev/1dee00e3727c9e479e1ed2bbbff7bef6 to your computer and use it in GitHub Desktop.
Save wanderindev/1dee00e3727c9e479e1ed2bbbff7bef6 to your computer and use it in GitHub Desktop.
class Solution(object):
def plus_one(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
carry = 0
index = 0
added = False
digits = digits[::-1]
while not added or carry:
if index < len(digits):
if digits[index] == 9:
digits[index] = 0
carry = 1
else:
digits[index] += 1
carry = 0
added = True
else:
digits.append(carry)
carry = 0
index += 1
return digits[::-1]
# Test cases
sol = Solution()
digits = [1, 2, 3]
assert sol.plus_one(digits) == [1, 2, 4]
digits = [4, 3, 2, 1]
assert sol.plus_one(digits) == [4, 3, 2, 2]
digits = [9]
assert sol.plus_one(digits) == [1, 0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment