4ms c++ easy solution


  • 2
    S
    vector<int> plusOne(vector<int>& digits) 
    {
        //empty array
        if (digits.size() == 0)
        {
            digits.push_back(1);
            return digits;
        }
        int count = digits.size() - 1;
        int carry = 0;
       
        for (int i = count; i >= 0; i--)
        {
            if (i == count)
            {
                carry = digits[i] + 1;
            }
            //stop the loop
            else if (carry == 0)
            {
                break;
            }
            else
            {
                carry += digits[i];
            }
            digits[i] = carry % 10;
            carry /= 10;
        }
        //whether there should be a new digit
        if (carry == 1)
        {
            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.