LeetCode小白菜笔记[15]:Plus One

LeetCode小白菜笔记[15]:Plus One

66. Plus One [easy]

题目如下:

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.

题目的意思是,把一个非负整数的每个位digit用list存起来,从高位到低位,然后给它+1s,把结果也用同样的结构返回。

code如下:

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

基本的加法原理,末位加一,整除和取模拿到进位carry和本位digits[i],然后其他位置加carry,也是整除和取模,最后如果最高位进位了,即位数改变,则在list前面补上个1。

出现的错误有,开始的时候 [1,] + somelist 用来拼接list 的语句错误。另外,只是最低位加一,其他位置加carry,开始时出错给每一位都加了一。低级错误,要改正。

37ms,42.78%

2018年2月9日20:35:02

有时你唱起歌,又是你沉默,有时你望着天空。——朴树 猎户星座

ps :
看了一下别人做的,发现,其实carry传到某一个digit的时候,如果变成carry = 0,那么就可以直接退出啦。。。上面自己写的这个程序是按照两个存成数组的大整数按位相加的最基本的方式写的,对于固定一个加数的可以简化。
另外,如果最后carry==1,也就是说超过数组长度进位了,那么肯定是10000……,原数肯定每一位都是9,因为+1s就能进位的只有这一种情况。

原文地址:https://www.cnblogs.com/morikokyuro/p/13256814.html