[LeetCode][Python]66. Plus One

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.

思路:一开始没看懂题目的意思,后来才明白是用一个列表代表一个非负整数,然后在最后一位加一,求新返回的列表。需要考虑的是空列表,列表最后一位小于9,最后一位等于9等情况。

要设置一个进位,初始值为1,从最后一个元素循环,依次给列表元素加一,如果最后的元素小于等于9,就直接返回加一后的list,因为没有进位。如果有进位,则置位0。最后在列表的第一个位置插入1。

#!usr/bin/env  
# -*-coding:utf-8 -*-
class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        if len(digits) == 0:
            return [1]
        carry = 1
        for i in xrange(len(digits)-1, -1, -1):
            digits[i] += carry
            if digits[i] <= 9:
                return digits
            else:
                digits[i] = 0

        digits.insert(0, 1)
        return digits

if __name__ == '__main__':
    sol = Solution()
    digits = [2, 1, 9, 9]
    print sol.plusOne(digits)
    原文作者:bluescorpio
    原文地址: https://www.jianshu.com/p/e33eb5689d6b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞