Plus One

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

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

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

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

O(n)

猜你喜欢

转载自www.cnblogs.com/ustcrliu/p/8985984.html