Convert a Number to Hexadecimal
Easy · Bit Manipulation · Math · String · Bit Manipulation
Problem
Given a 32-bit signed integer num, return its hexadecimal representation as a string.
- Use lowercase letters a to f for the digits 10 to 15.
- Write no leading zeros, except that zero itself is "0".
- Negative numbers are written in 32-bit two's complement, so they always come out as exactly eight hex digits.
Do not use a built-in number-to-hex conversion.
Examples
Input: num = 31 Output: "1f"
31 = 1 · 16 + 15, giving the digits 1 and f.
Input: num = -2 Output: "fffffffe"
In 32-bit two's complement, -2 is all ones except the lowest bit: fffffffe.
Input: num = 2748 Output: "abc"
2748 = 10 · 256 + 11 · 16 + 12, giving a, b and c.
Constraints
- -2^31 <= num <= 2^31 - 1
Approaches
- Baseline: write all 32 bits, then group by four — time O(1), space O(1)
Follow-up
The same loop converts to any base that is a power of two: three bits per octal digit, one bit per binary digit, five per base-32 digit. For a base that is not a power of two, such as 10 or 7, the digits come from repeated % base and // base on the value instead of from bit groups, and a negative number is usually written with a minus sign rather than in two's complement.
Related problems
Start free on Cariara · Coding problems · System design studio