[LeetCode] Plus One

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

将一个数的各个位存入数组中,让这个数加1,后返回一个加1后的结果数组。

如果最后一位是9,则这一位变成0。再判断前一位,如果该位置非9,则加1即可,也就是加上进位。

最后判断如果这个数字加1后各个位都为0,则需要在数组最前面加入进位1。

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        for (int i = digits.size() - 1; i >= 0; i--) {
            if (digits[i] == 9) {
                digits[i] = 0;
            }
            else {
                digits[i] += 1;
                return digits;
            }
        }
        if (digits[0] == 0)
            digits.insert(digits.begin(), 1);
        return digits;
    }
};
// 6 ms
原文地址:https://www.cnblogs.com/immjc/p/7436477.html