首页 > 其他 > 详细

66. Plus One

时间:2016-06-14 08:50:17      阅读:234      评论:0      收藏: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.

链接:  http://leetcode.com/problems/plus-one/

一刷,从最末尾加一,判断进位是否为0,0的时候不需要往前再进位,直接返回,否则继续向前计算。要注意的是

1. idx - 1否则下标过界

2. python swap two variables的trick: https://docs.python.org/2/reference/expressions.html#evaluation-orderhttp://stackoverflow.com/a/14836456

3. 最后一步还是要判断是否进位为1,不要光想着特殊情况忘记一般情况

4. python list.insert(index, value)两个输入变量的位置不要记错

class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        if not digits:
            return digits

        carry = 1
        
        for idx in range(len(digits), 0, -1):
            carry, digits[idx - 1] = (carry + digits[idx - 1]) / 10, (carry + digits[idx - 1]) % 10
            if not carry:
                return digits
        if carry:
            digits.insert(0, carry)
        return digits

 

66. Plus One

原文:http://www.cnblogs.com/panini/p/5582702.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!