Plus One python 题解

来源:互联网 发布:.net 免费商城源码 编辑:程序博客网 时间:2024/06/10 17:08

Plus One python 题解

题目大意:

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.

给定一个数组,这个数组代表一个数字,数字的最高位存在数组最前面,数字的最低位存在数组的最后面(符合书写习惯),输出该数字加1得到的数组
例如 input:[9,9] output:[1,0,0]

解题思路:

从数组的最低位开始遍历,若该位加一(这个1包含了进位的1和最开始的加的1)不产生进位的话,将该位加一返回结果即可,若该位产生进位,则将该位置为0,继续遍历即可,但要注意类似999+1=1000这种数组位数增加的情况,此时将最高位置为0然后在数组最前面加个1即可

python 代码实现如下:

class Solution:    # @param {integer[]} digits    # @return {integer[]}    def plusOne(self, digits):        length=len(digits)        i=length-1        while(i>=0):            if i==0:                if (digits[i]+1)>9:                    digits[i]=0                    result=[1]                    result.extend(digits)                    return result            if (digits[i]+1)<=9:                digits[i]+=1                return digits            else:                digits[i]=0                i-=1        return digits

多多交流

0 0
原创粉丝点击