my two 3ms ways to solve this(c++)


  • 0
    M

    class Solution {
    public:

    vector<int> plusOne(vector<int>& digits) {
        int i=1;
        while( digits[ digits.size()-i ] == 9 && (digits.size()-i) >= 0 ){
            if( digits.size()-i == 0) {
                //Method 1:*********************************************************** 
                //Add 0 to the begin of digits, other elements will be moved backward automatically. Refer to function vector.emplace().
                //digits.emplace( digits.begin() , 0); 
               //Method 2:*********************************************************** 
               //When all elements in digits are 9, simply push_back 0 to the end and reset all elements to 0 except  the first one which is set to 1;
                //digits.push_back(0);
                //digits[ 0 ] = 1;
                //return digits;
            }
            digits[ digits.size()-i ] = 0;
            i++;
        }
        digits[ digits.size()-i ]++;
        return digits;
        
    }
    

    };


Log in to reply
 

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