C Solution


  • 0
    T
    /**
     * Return an array of size *returnSize.
     * Note: The returned array must be malloced, assume caller calls free().
     */
    int* plusOne(int* digits, int digitsSize, int* returnSize) {
        bool done = false;
        int i, *ret;
        ret = malloc(sizeof(int)*(digitsSize+1));     
           
        for (i=digitsSize-1; i>=0; i--) {
            if (done)
                ret[i] = digits[i];
            else if(digits[i] < 9) {            
                ret[i]=digits[i]+1;            
                done = 1;
            } else {
                ret[i]= 0;
            }
        }
        if (ret[0] == 0) {
            ret[0]=1;
            ret[digitsSize] = 0;        
            *returnSize = digitsSize+1;
        } else
            *returnSize = digitsSize;
            
        return ret;    
    }
    

    Some bytes can be wasted, but there is no memory leak.


Log in to reply
 

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