[LeetCode] 66.Plus One

我的思路是很简单的,就是从后往前,加一个carry。

class Solution:
    def pivotIndex(self, nums: List[int]) -> int:
        if not nums:
            return -1
        
        total_sum = sum(nums)
        current_sum = 0
        
        for i in range(len(nums)):
            if current_sum == total_sum - current_sum - nums[i]:
                return i
            current_sum += nums[i]
            
            
        return -1

大家的思路都是先求出数值,直接+1,然后再转化成list,用str和int cast实现,以下是leetcode里面的几个典型写法

https://leetcode.com/problems/plus-one/discuss/24085/Simple-Python-solution-with-explanation-(Plus-One)

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)]

还有一个很有趣,是用reduce来写的

def plusOne(self, digits):
        num=reduce(lambda x,y:x*10+y,nums)+1
        return [int(i) for i in str(num)]

 

你可能感兴趣的:([LeetCode] 66.Plus One)