very simple C solution,10+lines,without extra memory


  • 0
    W
    char* toHex(int num) {
    	if(num==0) return "0";
    	unsigned int tmp=num;
    	char *ret=calloc(1,sizeof(char));
    	memset(ret,0,sizeof(char));
    	int count=0,mod=0;
    	if(num<0) tmp=~abs(num)+1;
    	while(tmp){
    		ret=realloc(ret,(count+2)*sizeof(char));
    		memmove(ret + 1, ret, (count + 1) * sizeof(char));
    		mod=tmp%16;
    		ret[0]=mod>9?mod-10+'a':mod+'0';
    		tmp/=16;
    		count++;
    	}
    	return ret;
    }
    

Log in to reply
 

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