Isaac Emmanuel
15 Jun 2024•EasyC++ / Python / TypeScript

Convert a Number to Hexadecimal

C++, Python and TypeScript solutions for Convert a Number to Hexadecimal.

The Convert a Number to Hexadecimal solutions are below.

Solution files

Python•convert-a-number-to-hexadecimal/synced-solution.py
def toHex(num):
    if num == 0:
        return "0"

    hex_chars = "0123456789abcdef"
    result = ""

    # Handle negative numbers using 32-bit representation
    if num < 0:
        num = (1 << 32) + num

    while num:
        result = hex_chars[num % 16] + result
        num //= 16

    return result
C++•convert-a-number-to-hexadecimal/synced-solution.cpp
class Solution {
public:
    string toHex(int num) {
        if (num == 0) return "0";

        string hex_chars = "0123456789abcdef";
        string result = "";

        unsigned int n = (unsigned int)num;

        while (n) {
            result = hex_chars[n % 16] + result;
            n /= 16;
        }

        return result;
    }
};
TypeScript•convert-a-number-to-hexadecimal/synced-solution.ts
function toHex(num: number): string {
    if (num === 0) return "0";

    const hexChars = "0123456789abcdef";
    let result = "";

    const n = num >>> 0;
    let temp = n;

    while (temp) {
        result = hexChars[temp % 16] + result;
        temp = Math.floor(temp / 16);
    }

    return result;
}