【LeetCode】Plus One

版权声明: https://blog.csdn.net/ysq96/article/details/90110960

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.

题意:

C++:

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int len=digits.size();
        digits[len-1]+=1;
        for(int i=digits.size()-1;i>=0;i--){
            if (digits[i] == 10)
            {
                digits[i] = 0;
                if (i == 0)
                {
                    digits[i] = 1;
                    digits.push_back(0);
                }
                else
                {
                    digits[i-1] += 1;	
                }	
            }
        }
        return digits;
    }
};

Python3:注意range范围是左闭右开

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        digits[-1] += 1
        list_len = len(digits)
        for index in range(list_len-1, -1, -1):
            if(digits[index] == 10):
                digits[index] = 0
                if(index == 0):
                    digits[index] = 1
                    digits.append(0)
                else:
                    digits[index-1] += 1
        return digits

可以把整个列表转成数字+1再转成列表

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        total_sum = 0
        res = []
        list_len = len(digits)
        for num in range(list_len):
            total_sum += digits[num]*pow(10, list_len - num - 1)
        total_sum += 1
        list_sum = list(str(total_sum))
        for i in list_sum:
            res.append(int(i))
        return res

猜你喜欢

转载自blog.csdn.net/ysq96/article/details/90110960
今日推荐