[LeetCode] 66.Plus One

Posted codingEskimo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode-66 Plus One

leetcode 66. Plus One

[LeetCode] 66. Plus One

[leetcode]66.Plus One

leetcode66 Plus One

[leetcode]66Plus One