leetcode with python:66. Plus One

题目:

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.

Increment the large integer by one and return the resulting array of digits.

用阵列表示一个数字,一样用阵列形式回传该数+1的结果
ex:input: [9]=>output: [1,0]

看似简单,但要考虑进位的状况(像上面的範例)

class Solution:    def plusOne(self, digits: List[int]) -> List[int]:        digits[-1]=digits[-1]+1                temp=0        for i in range(1,len(digits)+1):            digits[-i]=digits[-i]+temp            if digits[-i]<10:                temp=0                break            temp=digits[-i]//10            digits[-i]=digits[-i]%10                    if temp != 0:            digits.insert(0,temp)        return digits

先加一到个位数上,接着从个位开始侦测有没有进位
有进位就继续观测下一位,没进位就代表上面的值也不会变动了,可以提早结束程式
最后留意最高位是否有进位,有的话就insert进位值到最高位之上
这题reverse后再做应该会比较舒服,不过跟我一样用负index也行
最后执行时间32ms(faster than 94.21%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章