Skip to content

Instantly share code, notes, and snippets.

@yokolet
Created October 18, 2018 19:29
Show Gist options
  • Save yokolet/2d45fad71b9f5836ca32fd4a548600a1 to your computer and use it in GitHub Desktop.
Save yokolet/2d45fad71b9f5836ca32fd4a548600a1 to your computer and use it in GitHub Desktop.
Plus One
"""
Description:
Given a non-empty array of digits representing a non-negative integer, plus one to the
integer. The digits are stored such that the most significant digit is at the head of
the list, and each element in the array contain a single digit. You may assume the
integer does not contain any leading zero, except the number 0 itself.
Examples:
Input: [1,2,3]
Output: [1,2,4]
Input: [4,3,2,1]
Output: [4,3,2,2]
Input: [8,9,9,9]
Output: [9,0,0,0]
"""
def plusOne(digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
carry = 0
digits[-1] += 1
for i in range(len(digits)-1, -1, -1):
(carry, rem) = divmod(carry + digits[i], 10)
digits[i] = rem
if carry == 0: return digits
if carry == 1:
return [1] + [0]*len(digits)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment