My 0 ms C solution


  • 0
    char* toHex(int num) {
        if(0 == num) {
            char* r = (char*)malloc(2*sizeof(char));
            r[0] = '0';
            r[1]= '\0';
            return r;
        }
        char table[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char* res = (char*)malloc(9*sizeof(char));
        res[8] = '\0';
        unsigned long temp = num;
        if(num < 0) { // two’s complement
            temp = 1;
            temp <<= 32;
            temp = temp + num;
        }
        int i = 7;
        while(temp > 0 && i >= 0) {
            res[i--] = table[temp%16];
            temp /= 16;
        }
        return res + i + 1;
    }
    

Log in to reply
 

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