leetcode python3 简单题66. Plus One

1.编辑器

我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接

2.第六十六题

(1)题目
英文:
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

中文:
给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。

最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。

你可以假设除了整数 0 之外,这个整数不会以零开头。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/plus-one

(2)解法
① 直接法(耗时:32ms,内存:13.7M)

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        digits[len(digits)-1]+=1
        for indx in range(len(digits)-1, -1, -1):
            if indx!=0:
                if digits[indx]>=10:  # 其实,这里可以直接写成==10,因为加1进位肯定是原来位是9。
                    digits[indx]-=10
                    digits[indx-1]+=1
            else:
                if digits[indx]>=10:
                    digits[indx]-=10
                    digits.insert(0,1)
        return digits

注意:
1.这个是按照习惯从后面往前面加的方法,其实有点不方便,可以在最前面翻转一下digits: `digits[::-1]。
2.这个方法的关键是关注最高位indx=0的进位情况,如果还有进位,就必须在减10的基础上,在0位前插入1以表示最高位进位。

② 递归法(耗时:36ms,内存:13.8M)

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        def addOne(digits, indx):
            if indx == -1:
                digits.insert(0, 1)
                return digits
            digits[indx] += 1
            if digits[indx]==10:
                digits[indx] = 0
                return addOne(digits, indx-1)
            return digits
        return addOne(digits, len(digits)-1)

注意:
1.通过与直接法比较,其实可以看出,直接法中已经有了递归的感觉了。
2.递归的三要素:
① 终止条件:
当最高位还有进位时,会在最高位插入1进位,然后输出digits
② 问题的规模要减少:
addOne(digits, indx-1)这个就是在一次一次的减少问题规模
③ 调用相同的函数:
addOne

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值