力扣66. Plus One - 加一 (Python版本,两解题思路)

力扣66. 加一 (Python版本,两解题思路)

题目描述

Given a non-empty array of decimal digits representing a non-negative integer, increment 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 contains a single digit.

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

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

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

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

示例 1:

输入:digits = [1,2,3]
输出:[1,2,4]
解释:输入数组表示数字 123。

示例 2:

输入:digits = [4,3,2,1]
输出:[4,3,2,2]
解释:输入数组表示数字 4321。

示例 3:

输入:digits = [0]
输出:[1]

思路

需要考虑到几种情况:

  • 一般情况下末尾+1后不发生进位的(即末尾不为9),就直接在列表末尾元素+1. 如123-> 124
  • 如果末尾为9,+1后,此时存在两种情况:
    • 在中间进位停止。如1399 -> 1400.
    • 9999, 999这种数,999 -> 1000。也即是要对每一位进位,还要加多一位即列表长度+1.

方法1: 转换数据格式操作

转为数字后进行计算,再把计算后结果转为列表。这应该是最容易的办法了

代码:
class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        res = []
        digits = map(str, digits)
        digits = int(''.join(digits))+1
        #转为list
        digits = str(digits)
        for i in digits:
            res.append(int(i))
        return res     
Screen Shot 2021-04-02 at 10.14.38

方法2: 不转换格式,在列表上操作

设一个新的list, 从digits尾部开始检查,尾部是9的就移除该元素,并且在新的list插入0作为进位的标志。这个方法可以有效地检测到digits的尾部连续9的部分并能够停止在不为9的位置上。最后把这两个列表前后合并就是我们所要的答案。

如果是digits所有元素都为9的情况下,我们只需要加一个判断该情况语句,然后在新的list的头部插入新元素1即可。

图片示例如下:
在这里插入图片描述

代码:
class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        temp_lst = []
        # 遍历找9
        while digits and digits[-1] == 9:
            digits.pop()
            temp_lst.append(0)
        # digits 全部都是9
        if not digits:
            return [1] + temp_lst
        else:
            digits[-1] += 1
            return digits + temp_lst
       

总结

上面的两种方法算法上差不多。都是O(n)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值