LeetCode Plus One

来源:互联网 发布:网络机顶盒安装步骤 编辑:程序博客网 时间:2024/06/08 16:26

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 digitsif __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) 来获得相关源码。

0 0
原创粉丝点击