Created
October 18, 2018 19:29
-
-
Save yokolet/2d45fad71b9f5836ca32fd4a548600a1 to your computer and use it in GitHub Desktop.
Plus One
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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