Leetcode_Array -- 66. Plus One [easy]

本文详细解析了一种常见的数组操作算法——给定一个非空数组表示的非负整数,在此基础上加一。通过两个示例说明了算法的具体实现,包括Python代码示例,展示了如何在数组的每个元素上进行操作,以及当数组元素全为9时的特殊情况处理。

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.
给定一个非空数组来表示一个非负整数,在这个整数上加一

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

Solutions:

Python

(1)
class Solution:
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        digits = list(map(str,digits))
        digit = list(str(int(''.join(digits))+1))
        digits = list(map(int,digit))
        return digits

(2)
#方法2和下面的C++思想相同,注意本次的注解部分的小技巧
class Solution:
    def plusOne(self, digits):
        for i in range(len(digits)):
            if digits[~i] < 9:   #这里的~波浪号表示倒序输出
                digits[~i] += 1
                return digits
            digits[~i] = 0
        return [1] + [0] * len(digits)

列表在遍历的时候i前面加上波浪号则为倒序输出,在网上还没有查到相关解释,下面写个测试代码,解释一下这个小技巧。

Python

 =============================
A = [3,4,5,6,7,8]
for i in range(len(A)):
	print(~i)
------------------------------
[output]:-1,-2,-3,-4,-5,-6

 =============================
A = [3,4,5,6,7,8]
for i in range(len(A)):
	print(-i)
------------------------------
[output]:0,-1,-2,-3,-4,-5

 =============================
A = [3,4,5,6,7,8]
for i in range(len(A)):
	print(i)
------------------------------
[output]:0,1,2,3,4,5

 =============================
for i in range(len(A)):
	print(A[~i])
------------------------------
[output]:8,7,6,5,4,3

C++

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        for(int i = digits.size()-1;i>=0;i--){
            if (digits[i] != 9){   #如果digits[i]不为9,直接加一,然后退出
                digits[i]++;
                break;
            }
            digits[i] = 0;   #如果digits[i]为9的时候,将digits[i]置为0
        }
        if (digits[0] == 0){   #digits[0] = 0表明了各个位置都是9,则需要在digits前面在加入一个一
            digits.insert(digits.begin(),1);
        }
        return digits;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值