My C++ Solution that beats 100%


  • 0
    E

    My C++ solution adds one first and then fix the digits from right to left
    (change greater-than-9 digits to 9 and add one to the following digits). This solution is 100% faster than the previous solutions. Any feedback is welcome. Thanks!

    class Solution {
    public:
        // add one slot to the beginning of the vector
        void resize(vector<int>& digits) {
        	digits.push_back(0);
        	// moving right all elements
        	for (int i = digits.size() - 1; i > 0; --i) {
        		digits[i] = digits[i-1];
        	}
        	digits[0] = 0;
        }
        
        vector<int> plusOne(vector<int>& digits) {
            int n = digits.size() - 1;
            ++digits[n];
            while (digits[n] > 9) { 	
                if (n == 0) {
                	resize(digits);
                	++n;
                } 
                digits[n] = 0;
                ++digits[--n];
            }
            return digits;
        }
    };
    
    

Log in to reply
 

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