Easy question with easy thoughts.


  • 0
    J
    class Solution {
    public:
        vector<int> plusOne(vector<int> &digits) {
            vector<int> ret;
            bool add = false;
            for(int i = digits.size() - 1; i >= 0; i--)
            {
                if(i == digits.size() - 1)
                {
                    if(digits[i] == 9)
                    {
                        ret.push_back(0);
                        add = true;
                    }
                    else
                        ret.push_back(digits[i] + 1);
                }
                else
                {
                    if(add == true)
                    {
                        if(digits[i] <= 8)
                        {
                            add = false;
                            ret.push_back(digits[i] + 1);
                        }
                        else
                        {
                            ret.push_back(0);
                        }
                    }
                    else
                        ret.push_back(digits[i]);
                }
            }
            if(add == true)
                ret.push_back(1);
            reverse(ret.begin(), ret.end());
            return ret;
        }
    };

Log in to reply
 

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