Leetcode 66. Plus One

本文介绍了一种使用Python实现的算法,该算法能够对一个非空数组表示的非负整数进行加一操作。文章详细解释了实现过程,包括如何处理进位,并提供了具体的代码示例。

题目原文:

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.


即通过非空数组来表示一个数,数组不会有前导零。对数组表示的数加一,返回对应的数组。

如[1,2]表示12,因此加一得到13,返回[1,3]。

特别地,若有进位发生,[9]加一得到[1,0]。


用python编写代码如下:

class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        digits[-1] += 1
        index = -1
        while digits[index] == 10:
            digits[index] = 0
            if -index == len(digits):
                digits.insert(0,1)
                break
            index -= 1
            digits[index] += 1
        return digits

思路:

从最后一位开始,对列表元素加一,若结果不为10,则返回列表,否则将该元素置为0,并对前一位重复该操作。若当前元素是列表中最后一个元素且结果为10,则在列表首部插入1。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值