Skip to content

405. Convert a Number to Hexadecimal 👍

  • Time: $O(\log_{16} n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  string toHex(unsigned num) {
    if (num == 0)
      return "0";

    constexpr char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7',
                            '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    string ans;

    while (num != 0) {
      ans += hex[num & 0xf];
      num >>= 4;
    }

    ranges::reverse(ans);
    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public String toHex(int num) {
    if (num == 0)
      return "0";

    final char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7',
                        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    StringBuilder sb = new StringBuilder();

    while (num != 0) {
      sb.append(hex[num & 0xf]);
      num >>>= 4;
    }

    return sb.reverse().toString();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def toHex(self, num: int) -> str:
    if num == 0:
      return '0'

    hex = '0123456789abcdef'
    ans = []

    # Handling negative numbers by using 32-bit unsigned representation Python's
    # bitwise operation works on signed numbers, so we convert to 32-bit
    # unsigned for negative numbers.
    if num < 0:
      num += 2**32

    while num > 0:
      ans.append(hex[num & 0xF])
      num >>= 4

    return ''.join(reversed(ans))