LeetCode 66. Plus one (C ++)

Problem:
Given a non-negative integer represented by a non-empty array of integers, add one to the number.
The highest digit is stored in the first digit of the array, and each element in the array stores only a single digit.
You can assume that this integer will not start with zero except for the integer 0.

Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The input array represents the number 123.

Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The input array represents the number 4321.

Problem-solving ideas:
Simulate addition operations.
It is especially important to note that when calculating numbers like 9,99 and 999, the number of digits will be one more bit, which becomes 10,100 and 1000.

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int carry = 1;
        for(int i=digits.size()-1;i>=0;i--){
            if(digits[i]+carry>9){ //判断加一后是否达到进位条件
                digits[i] = 0;
            }else {
                digits[i] += carry;
                carry = 0;
                break; //之后的数就没必要计算了
            }
        }
        if(1 == carry){ //如果一直进位的话,比如9,99和999之类的数字
            digits.insert(digits.begin(),1); //在第一个数字前插入1
        }
        return digits;
    }
};
Published 111 original articles · won praise 2 · Views 3533

Guess you like

Origin blog.csdn.net/m0_38088647/article/details/101855553