#66. Plus One

2017-04-12  本文已影响15人  Double_E

https://leetcode.com/problems/plus-one/#/description

Given a non-negative integer represented as a non-empty array 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.

翻译

分析

# Time O(n)
class Solution(object):
    def plusOne(self, digits):
        carry = 0
        for i in range(len(digits)-1, -1, -1):
            digits[i] += carry
            if i == len(digits) - 1:
                digits[i] += 1
            if digits[i] == 10:
                digits[i] = 0
                carry = 1 # 进位标志
            else:
                carry = 0
        if carry == 1:
            digits.insert(0, 1)
        return digits 
上一篇下一篇

猜你喜欢

热点阅读