Q66 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.

解题思路:

这道题的意思是给你一个非负整数,它被拆成一个列表,如 939 变成 [9,3,9],然后让你实现+1操作。简单方法就是从后往前判断各个数字,逢九进1。

Python实现:
class Solution:
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        if digits[-1] != 9:  # 如果各位不为9,则直接加1即可
            digits[-1] += 1
            return digits
        else:
            i = len(digits) - 1
            bit = 1
            while i >= 0:
                if digits[i] + bit == 10:
                    digits[i] = 0
                    bit = 1
                else:
                    digits[i] += 1
                    bit = 0
                    break  # 不再向前进位
                i -= 1
        if bit == 1:  # 如果最前面仍然产生进位,则插入1,比如 99 -> 100
            digits.insert(0,1)
        return digits

a = [2,4,9,3,9]
b = Solution()  # 24940
print(b.plusOne(a))

你可能感兴趣的:(Q66 Plus One)