美文网首页
#66. Plus One

#66. Plus One

作者: Double_E | 来源:发表于2017-04-12 21:29 被阅读15次

    https://leetcode.com/problems/plus-one/#/description

    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.

    翻译

    • 给定一个代表非负整数的列表,其中每一个值代表该位的数值。
    • 对该整数+1,返回新的列表
    • 比如 19=[1,9] 19+1=20=[2, 0]

    分析

    • 设置进位符 carry=0
    • 逆序遍历列表
    • 所有元素均+carry list[i] += carry
    • 若list[i]+carry = 10,则list[i] = 0, carry = 1; 否则carry = 0
    • 若遍历结束时,carry == 1,则需要新加入一个[1],放入列表最前面,即
    • [9] ->[1, 0]
    # Time O(n)
    class Solution(object):
        def plusOne(self, digits):
            carry = 0
            for i in range(len(digits)-1, -1, -1):
                digits[i] += carry
                if i == len(digits) - 1:
                    digits[i] += 1
                if digits[i] == 10:
                    digits[i] = 0
                    carry = 1 # 进位标志
                else:
                    carry = 0
            if carry == 1:
                digits.insert(0, 1)
            return digits 
    

    相关文章

      网友评论

          本文标题:#66. Plus One

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