字符串可以按位获得和列表生成式-【leetcode66-plus one】

来源:互联网 发布:淘宝卖什么利润大 编辑:程序博客网 时间:2024/06/11 04:14

一、题目

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.

即【9,0】=90,90+1=91,91=【9,1】

二、渣渣方法1

class Solution(object):    def plusOne(self, digits):        """        :type digits: List[int]        :rtype: List[int]        """        n = len(digits)        nums = 0        for i in range(n):            nums += digits[i]*10**(n-1)            n = n-1        nums += 1        n = len(digits)        t = 10**(n-1)        if (nums%t < t) and (nums != 10**n):        for i in range(n):        digits[i] = nums/(10**(n-1-i))        nums = nums - digits[i]*(10**(n-1-i))        else:            digits = []            for i in range(n+1):                digits.append(nums/(10**(n-i)))                nums = nums - digits[i]*(10**(n-i))        return digits

三、leetcode solution 2

def plusOne(digits):    num = 0    for i in range(len(digits)):    num += digits[i] * pow(10, (len(digits)-1-i))    return [int(i) for i in str(num+1)]

四、优化点

1、在【9,0】=90这一步,少用一个n参数,将i带入即可

2、主要在91=【9,1】这一步,最重要的是了解到字符串可以按位获得单个字符,这样就避免算法一较为复杂的写法,同时运用列表生成式。

五、leetcode solution 3:迭代

def plusOne(self, digits):    """    :type digits: List[int]    :rtype: List[int]    """    if len(digits) == 0:        digits = [1]    elif digits[-1] == 9:        digits = self.plusOne(digits[:-1])        digits.extend([0])    else:        digits[-1] += 1    return digits



原创粉丝点击