niuworld/LeetCodeSolution

66.Plus One

Opened this issue · 0 comments

Question:

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

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

Solution:

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

Note: use of vector::insert