Make writing a habit together! This is the 8th day of my participation in the “Gold Digging Day New Plan · April More Text Challenge”. Click here for more details.

I. Problem description

Given a non-negative integer represented by a non-empty array of integers, add one to that number.

The highest digit is stored at the beginning of an array, where each element stores only a single digit.

You can assume that this integer does not start with zero, except for the integer 0.

Title link: Plus one.

Two, the title requirements

Sample 1

Input: digits = [1,2,3] output: [1,2,4] explanation: input array represents the number 123.Copy the code

The sample 2

Input: nums = [9,9] output: [1,0,0]Copy the code

inspection

1. Mathematical ideas and rounding 2. The recommended time is 15~35minCopy the code

Third, problem analysis

When I first read this problem, I thought it was so easy, and the last place was +1. When I submitted it, I found out that the question asked for one base of 10, which is equivalent to the operation of base 10.

First, we’re going to store it at subscript 0, and then we’re going to flip the array to avoid a lack of carry.

So let’s say r is the carry, if we go to 10, we start at 1, because we’re going to add 1, we just need to add the index to the carry r.

And then there’s a special case, where r has to carry forward at the end, but at the end of the index, so we have to fill it up by one.

Four, coding implementation

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int i,n=digits.size(),r=1,k;// Initialize the data
        vector<int>v;// Store data
        for(i=0; i<n; i++)// Array is stored from 0 to n-1
        {
            k=digits[n- 1-i]+r;/ / calculate
            v.push_back(k%10);/ / store
            r=k/10;// Determine whether to carry forward
        }
        if(r! =0)// Also need to carry forward
            v.push_back(r);
        reverse(v.begin(),v.end());// Flip the array
        return v;// Output the result}};Copy the code

V. Test results