Convert a Number to Hexadecimal

Easy
420.

Convert a Number to Hexadecimal

Convert a Number to Hexadecimal is an easy coding problem on math and bit manipulation, asked in Amazon, Microsoft and Adobe interviews.

Given a 32-bit integer num, return its hexadecimal representation as a lowercase string.

Negative numbers use two's complement. The result must not have leading zeros, except that zero itself is "0". Do not use any built-in conversion function.

Example 1

Input
num = 26
Output
1a

Example 2

Input
num = -1
Output
ffffffff

Example 3

Input
num = 0
Output
0

Constraints

  • -2147483648 <= num <= 2147483647
Write your solution here. Running it against the tests needs a free account — what you type comes with you.Sign in to run
/**
 * @param {number} num
 * @return {string}
 */
var toHex = function(num) {
    // Write your code here
    
};

Sign in to run your own test cases

Sign in

Convert a Number to Hexadecimal — Problem & Solution

Convert a Number to Hexadecimal solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.

Convert a Number to Hexadecimal is an easy coding problem on math and bit manipulation, asked in Amazon, Microsoft and Adobe interviews.

  • Difficulty: Easy
  • Topics: Math, Bit Manipulation
  • Asked at: Amazon, Microsoft, Adobe
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

Given a 32-bit integer num, return its hexadecimal representation as a lowercase string.

Negative numbers use two's complement. The result must not have leading zeros, except that zero itself is "0". Do not use any built-in conversion function.

Example 1

Input: num = 26
Output: 1a

Example 2

Input: num = -1
Output: ffffffff

Example 3

Input: num = 0
Output: 0

Constraints

  • -2147483648 <= num <= 2147483647

Hints for Convert a Number to Hexadecimal

  1. Hint 1

    Work on the unsigned 32-bit value: for a negative num, that is num + 2^32.

  2. Hint 2

    Repeatedly take the low four bits and map them through "0123456789abcdef".

  3. Hint 3

    Build the string from the least significant digit, so prepend rather than append.

How to solve Convert a Number to Hexadecimal

Work on the unsigned 32-bit value (add 2³² to negatives), then peel four bits at a time and map through 0123456789abcdef.

Approach

  1. Return "0" for zero.
  2. Convert a negative to num + 2³².
  3. Repeatedly take v % 16 as a digit and divide by 16, prepending.

Why it works

Two's complement hex is the hex of the unsigned reinterpretation, and each hex digit is exactly four bits.

Complexity

  • Time — O(8)
  • Space — O(1)

Pitfalls

  • In a language with arithmetic right shift, mask with 0xF and use a logical shift, or the loop never ends on negatives.

Reference solution

Python

def toHex(num: int) -> str:
    if num == 0:
        return "0"
    digits = "0123456789abcdef"
    v = num if num > 0 else num + (1 << 32)
    out = ""
    while v:
        out = digits[v % 16] + out
        v //= 16
    return out

Java

public static String toHex(int num) {
    if (num == 0) return "0";
    String digits = "0123456789abcdef";
    long v = num < 0 ? (long) num + 4294967296L : (long) num;
    StringBuilder out = new StringBuilder();
    while (v > 0) {
        out.insert(0, digits.charAt((int) (v % 16)));
        v /= 16;
    }
    return out.toString();
}

C++

string toHex(int num) {
    if (num == 0) return "0";
    string digits = "0123456789abcdef";
    long long v = num < 0 ? (long long) num + 4294967296LL : (long long) num;
    string out;
    while (v > 0) {
        out = string(1, digits[(int) (v % 16)]) + out;
        v /= 16;
    }
    return out;
}

JavaScript

var toHex = function(num) {
    if (num === 0) return "0";
    const digits = "0123456789abcdef";
    let v = num < 0 ? num + 4294967296 : num;
    let out = "";
    while (v > 0) {
        out = digits.charAt(v % 16) + out;
        v = Math.floor(v / 16);
    }
    return out;
};

Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 337 math problems · the whole catalogue

Learn the technique: Bit Manipulation