美文网首页
Q66 Plus One

Q66 Plus One

作者: 牛奶芝麻 | 来源:发表于2018-02-28 16:31 被阅读11次

    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

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