Plus One
Given a non-negative integer represented as anon-emptyarray of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits = list(reversed(digits))
digits[0] += 1
i, carry = 0, 0
while i < len(digits):
next_carry = (digits[i] + carry) / 10
digits[i] = (digits[i] + carry) % 10
i, carry = i + 1, next_carry
if carry > 0:
digits.append(carry)
return list(reversed(digits))
Last updated
Was this helpful?