首页 > 其他 > 详细

LeetCode Plus One

时间:2016-01-18 10:33:47      阅读:227      评论:0      收藏:0      [点我收藏+]

LeetCode解题之Plus One


原题

给一个由包含一串数字的列表组成的非负整数加上一。

注意点:

  • 列表前面的数字表示高位
  • 注意最高位也可能进位

例子:

输入: [1, 2, 3, 4, 9]

输出: [1, 2, 3, 5, 0]

解题思路

从低位到高位,如果后一位有进位的话,那么该位要加上一,否则退出循环。如果最高位也进位,那么在列表前要插入一个一。

AC源码

class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        carry = 1
        for i in range(len(digits) - 1, -1, -1):
            digits[i] += carry
            if digits[i] < 10:
                carry = 0
                break
            else:
                digits[i] -= 10
        if carry == 1:
            digits.insert(0, 1)
        return digits


if __name__ == "__main__":
    assert Solution().plusOne([1, 2, 3, 4, 9]) == [1, 2, 3, 5, 0]
    assert Solution().plusOne([9]) == [1, 0]

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

LeetCode Plus One

原文:http://blog.csdn.net/u013291394/article/details/50534662

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!