Accepted C++ solution at 4ms, no extra memory with explanation.


  • 1
    P

    The algorithm is simple, enumerate numbers starting from leas significant and increment it.

    If result of increment is not equal 10, we are done, return. If not, set it to 0 and go to the next value;

    If while loop go through, then the input is [9],[9]...[9],[9] and we need to insert 1 in the front.

    vector<int> plusOne(vector<int> &digits) {
        int size=digits.size();
        if(size==0) return digits;
        
        while(--size >= 0)
        {
            if(++digits[size]!=10)
            {
                return digits;
            }
            digits[size]=0;
        }
        
        digits.insert(digits.begin(),1);
        return digits;
    }

Log in to reply
 

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