66 Plus One

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. (For 123, 1 is the most significant number.)

Solution

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int n = digits.size();
        reverse(digits.begin(), digits.end());
        int add = 1;
        for ( int i = 0; i <= n-1; i++ ) {
            int v = digits[i] + add;
            digits[i] = v%10;
            add = v/10;
        }
        if ( add == 1 ) digits.push_back(1);
        reverse(digits.begin(), digits.end());
        return digits;
    }
};

Notes
Reverse a vector:

reverse(v.begin(), v.end());

results matching ""

    No results matching ""