[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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,790评论 0 33
  • 问题描述: 对用数组表示的数字进行加一操作 示例:输入:[9,9] 输出:[1,0,0]输入...
    小歪与大白兔阅读 135评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,238评论 19 139
  • Given a non-negative integer represented as a non-empty a...
    ShutLove阅读 252评论 0 0
  • 早晨,天气阴转多云,心情也是,思维跳跃性太高,有些许的不高兴,饮食也无一例外,可是我只是想做一颗勇敢的平凡的豆子...
    乔思麻麻阅读 243评论 0 0