4ms 8-lines C++ Solution


  • 1

    The idea is just to perform the addition from right to left as usual :-)

    Note that the result may be longer than the original digits by 1 number (the carry).

    class Solution {
    public:
        vector<int> plusOne(vector<int> &digits) {
            int c = 1, n = digits.size();
            vector<int> sum(n, 0);
            for(int i = n - 1; i >= 0; i--) {
                int val = digits[i] + c; 
                sum[i] = val % 10;
                c = val / 10;
            }
            if(c) sum.insert(sum.begin(), c);
            return sum;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.