What' wrong with my c solution??Last executed input: [1]


  • 1
    R
    int *plusOne(int *digits, int len, int *newLen) {
    	int n = len-1;
    	while(n>=0){
    		if(digits[n]<9){
    			digits[n]+=1;
    			*newLen=len;
    
    			return digits;
    		} else {
    			digits[n] =0;
    			--n;
    		}
    	}
    
    	digits = (int *)realloc(digits,(len+1)*sizeof(int));
    	if(NULL == digits)
    		exit(-1);
    
    	*newLen = len +1;
    	n = len;
    	while(n>0){
    		digits[n] = digits[n-1];
    		--n;
    	}
    	digits[0]=1;
    	return digits;
    }
    

    code above got a runtime error on OJ. and Last executed input: [1].
    but it runs well on my own machine.even with the last UC. I can't figure it out.help me please~


  • 0
    S

    i have the same problem!runtime error and Last executed input: [1].


  • 0
    R

    I rewrite it with cpp,and passed all UCs.Still don't know what's wrong with my c solution.Seems like there are some accepted C solutions~


  • 0
    H

    i have the same problem!runtime error and Last executed input: [1]. who can help us?


  • 0
    D

    i have the same problem! can't find out why. System's problem?


  • 1
    L

    probably because int *digit is in stack and you wont be able to realloc the size.


  • 0
    R

    Well, I think u r right. last time I check,they have changed the signature of function and fixed this problem.


  • 0
    R

    struct IntArray* plusOne(struct IntArray* digits) {
    int n = digits->size-1;
    int *ele= digits->elements;
    while(n>=0){
    if(ele[n]<9){
    ele[n]+=1;

            return digits;
        } else {
            ele[n] =0;
            --n;
        };
    };
    
    n=digits->size;
    digits->size+=1;
    
    ele = (int *)realloc(ele,(n+1)*sizeof(int));
    if(NULL == ele)
        exit(-1);
    
    while(n>0){
        ele[n] = ele[n-1];
        --n;
    };
    ele[0]=1;
    digits->elements=ele;
    return digits;
    

    }

    the code above could be accepted.


  • 0

    realloc(*ptr,...) I think ptr should pointer to the space allocated by heap.

    But frome the function , we cannot know whether the digits is allocated by heap malloc()

    So you got the error.

    You can rewrite your code like this. ^_^

    int *plusOne(int *digits, int len, int *newLen) {
    	int n = len-1;
    	while(n>=0){
    		if(digits[n]<9){
    			digits[n]+=1;
    			*newLen=len;
    
    			return digits;
    		} else {
    			digits[n] =0;
    			--n;
    		}
    	}
        
        
        
    	digits = (int *)malloc((len+1)*sizeof(int));
    	if(NULL == digits)
    		exit(-1);
    
            *newLen=len+1;
    	n = len ;
    
    	while(n>0){
    		digits[n] = 0;
    		--n;
    	}
    	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.