LeetCode刷题笔记--66. Plus One

66. Plus One

Easy

7531352FavoriteShare

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.

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        
        int j = digits.size();
        vector<int> addv(digits.size()-1,0);
        addv.push_back(1);
        
        bool flag = false;

        for (int i = j - 1; i >= 0; i--)
        {
            int p = flag ? 1 : 0;
            digits[i] = addv[i] + digits[i] + p;
            if (digits[i] == 10) { digits[i] = 0; flag = true; }
            else flag = false;
        }

        if (flag)
        {
            digits.push_back(digits[j - 1]);
            int i = j;//这里要特别注意,因为vector增大了1,所以不能是j-1,否则报错
            while (i>0)
            {
                digits[i] = digits[i - 1];
                i--;
            }
        
            digits[0] = 1;
        }

        return digits;
   
    }
};

猜你喜欢

转载自blog.csdn.net/vivian0239/article/details/87876067