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.

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

Approaches

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

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…