PU Convert a Number to Hexadecimal

Jan 01, 1970

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

  • All letters in hexadecimal (a-f) must be in lowercase.
  • The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
  • The given number is guaranteed to fit within the range of a 32-bit signed integer.
  • You must not use any method provided by the library which converts/formats the number to hex directly.

Example 1:

  • Input: 26
  • Output: "1a"

Example 2:

  • Input: -1
  • Output: "ffffffff"

C Solution:

void reverse(char *s, char *e) {
    while (s <= e) {
        char sc = *s < 10 ? *s + '0' : *s + 'a' - 10;
        char ec = *e < 10 ? *e + '0' : *e + 'a' - 10;
        *s++ = ec;
        *e-- = sc;
    }
}

char* toHex(int num) {
    char *res = calloc(9, sizeof(char));
    if (num == 0) {
        res[0] = '0';
        return res;
    }
    if (num == -2147483648) {
        res[0] = '8';
        memset(res + 1, '0', 7);
        return res;
    }
    int minus = 0;
    if (num < 0) {
        minus = 1;
        num = -num;
    }
    char *p = res;
    while (num) {
        *p++ = num % 16;
        num /= 16;
    }
    if (!minus) {
        reverse(res, p - 1);
        return res;
    }
    int i, carry = 1;
    for (i = 0; i < 8; i++) {
        int tmp = 15 - res[i] + carry;
        if (tmp == 16) {
            res[i] = 0;
            carry = 1;
        }
        else {
            res[i] = tmp;
            carry = 0;
        }
    }
    reverse(res, res + 7);
    return res;
}

C Solution 2:

void reverse(char *s, char *e) {
    while (s < e) {
        char c = *s;
        *s++ = *e;
        *e-- = c;
    }
}
char* toHex(int num) {
    char *res = calloc(9, sizeof(char));
    res[0] = '0';
    unsigned _num = num;
    char *p = res;
    while (_num) {
        int val = _num & 15;
        *p++ = val > 9 ? val + 'a' - 10 : val + '0';
        _num >>= 4;
    }
    reverse(res, p - 1);
    return res;
}

Summary:

  • Don't overthink.

LeetCode: 405. Convert a Number to Hexadecimal