Yingying

你必须非常努力,才能看起来毫不费力

66. Plus One*

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

My code:

class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        n = len(digits)
        carry = 1
        for i  in range(n-1,-1,-1):
            digits[i] = digits[i]+carry
            if digits[i]==10:
                digits[i] =0
            else:
                carry = 0
                break
        if carry ==1:
            digits.insert(0,1)
        return digits

Optimized:

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


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/alwaystry/article/details/52356184
个人分类: leetcode
上一篇219. Contains Duplicate II *
下一篇27. Remove Element*
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭