美文网首页
每天(?)一道Leetcode(6) Plus One

每天(?)一道Leetcode(6) Plus One

作者: 失业生1981 | 来源:发表于2019-01-20 08:50 被阅读0次

Array

066. Plus One

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
即:十进制加法 但每次只加一

Solutions

从个位开始加,如果当前位置为9,则加1之后为0,前一位继续加1,直到当前位置不是9,加1之后结束。
需要注意的是所给数字全为9的情况,如99

class Solution:
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        
        for i in reversed(range(len(digits))):
            if digits[i] == 9:
                digits[i] = 0
            else:
                digits[i] += 1
                return digits
        digits[0] = 1
        digits.append(0)
        return digits

相关文章

网友评论

      本文标题:每天(?)一道Leetcode(6) Plus One

      本文链接:https://www.haomeiwen.com/subject/ucztjqtx.html