clueless coding // TODO: be smarter

LeetCode 405. Convert a Number to Hexadecimal: C++ Solution



Problem Statement


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

Output any letters in your hexadecimal representation in lowercase.

Do not output a hexadecimal representation with leading 0s.

If the input is 0, represent it with a single ‘0’.

You can assume that the given number is guaranteed fits in a 32 bit signed integer.

Do not use any libraries or built-in methods that perform the conversion automatically.

Function Signature (C++):
  string toHex(int num)

Inputs:
  num = 26

Outputs:
  "1a"

Inputs:
  num = -1
Outputs:
  "ffffffff"



TL;DR Code Solution


string toHex(int num) {
    if (num == 0) return "0";
    string result;
    int count = 0;
    while (num && count++ < 8) {
        result = HEX[(num & 0xf)] + result;
        num >>= 4;
    }
    return result;
}