Share My Code Using resize()


  • 0
    class Solution
    {
    	public:
    	vector<int> plusOne(vector<int>& digits)
    	{
    		if(!digits.size())
    		{
    			return{};
    		}
    		if(digits[0] < 0) { return{}; }
    
    		int carry = 0;
    		int i = digits.size() - 1;
    		++digits[i];
    		if(digits[i] == 10)
    		{
    			digits[i] = 0;
    			carry = 1;
    		}
    		
    		for(--i; i >= 0; --i)
    		{
    			digits[i] += carry;
    			if(digits[i] == 10)
    			{
    				digits[i] = 0;
    				carry = 1;
    			}
    			else{
    			    carry=0;
    			}
    		}
    		if(1 == carry)
    		{
    			auto len = digits.size();
    			digits.clear();
    			digits.resize(len+1, 0);
    			digits[0] = 1;
    		}
    		return digits;	
    	}
    };
    

Log in to reply
 

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