[牛客网-Leetcode] #Array medium plus-one

Number plus one plus-one

Title description

Given a non-negative integer represented by an array of numbers, please add 1 to the integer.
Given a non-negative number represented as an array of digits, plus one to the number.

Example

Example 1
input

[1]

Output

[2]

Example 2
input

[1,2,3]

Output

[1,2,4]

Problem-solving ideas

  • In essence, it is the addition of large integers, the carry flag is set, and the traversal starts from the low bit. Each time if a carry occurs, the current bit and the carry flag carry are modified. If there is still a carry after the traversal, the carry is added to the high position.
class Solution {
    
    
public:
    vector<int> plusOne(vector<int>& digits) {
    
    
        int one(1), carry(0);  //待加整数和进位
        int size = (int)digits.size();
        //由于只需要加一次1,所以不用放在循环里,直接初始化时相加即可
        digits[size - 1] += one;
        for(int i = size - 1; i >= 0; i --) {
    
    
            digits[i] += carry;
            carry = digits[i] / 10;
            digits[i] %= 10;
        }
        //如果仍有进位,就在最高位之后补上进位
        if(carry) {
    
    
            digits.insert(digits.begin(), carry);
        }
        return digits;
    }
};

Guess you like

Origin blog.csdn.net/cys975900334/article/details/106613823