关闭

66. Plus One*

49人阅读 评论(0) 收藏 举报
分类:

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


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:45511次
    • 积分:3737
    • 等级:
    • 排名:第8623名
    • 原创:331篇
    • 转载:87篇
    • 译文:0篇
    • 评论:9条
    最新评论