[66] leetcode plus one (array)

Topic links: https://leetcode-cn.com/problems/plus-one/

Title Description

Given a non-negative integer nonempty array of integers represented, on the basis of the number plus one.

Most significant digit stored in the first array, each element of the array stores a number only.

You may assume that in addition to the integer 0, the integer does not begin with a zero.

Example 1:

输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。

Example 2:

输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。

Thinking

Bitwise from the back

Code

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

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/zjwreal/article/details/94603263