LeetCode 66 Plus One (Python)

Posted by 小明MaxMing on July 6, 2020

题目

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.

解题思路

从后向前遍历,如果是9变成0,不是9就+1,并返回结果,要处理全是9的情况

代码

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        for i in range(len(digits)-1, -1, -1):
            if digits[i] == 9:
                digits[i] = 0
            else:
                digits[i] += 1
                return digits
        return [1] + digits

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅