leetcode--Plus One

来源:互联网 发布:仿糗事百科源码 编辑:程序博客网 时间:2024/06/09 18:22

题目:难度(Easy)

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.
Tags:Array Math
Similar Problems:(M) Multiply Strings (E) Add Binary
分析:用数组存数的各个数位,数组的靠前的位置数位越大,如[1,2,3]表示123,加1编程[1,2,4]
代码实现:

class Solution(object):    def plusOne(self, digits):        """        :type digits: List[int]        :rtype: List[int]        """        digits.reverse()        #进行加1操作        digits[0]+=1        #update digits数组,divmod函数返回(商,余数)        for i in range(len(digits)-1):            carry, digits[i] = divmod(digits[i], 10)            digits[i+1] += carry        if digits[len(digits)-1] > 9:            digits[len(digits)-1] %= 10            digits.append(1)        digits.reverse()        return digits


0 0
原创粉丝点击