Show problems as
Classic problem #405EasyMathStringBit Manipulation

Convert a Number to Hexadecimal

Real-world version: Writing a Signed Reading in Base Sixteen
Tracked in this browser only
Read Convert a Number to Hexadecimal on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A reading num is a whole number that fits in thirty-two bits.

Write it in base sixteen, using '0' through '9' and then the lowercase letters 'a' through 'f'. A negative reading is written as its pattern over thirty-two bits taken as an unsigned number, which is the reading plus two raised to the thirty-second. Write no leading zero, except that the reading 0 is written as the single character "0".

Return that spelling.

Examples

Example 1

Input
num = 255
Output
"ff"

Two hundred and fifty-five is fifteen sixteens plus fifteen, and fifteen is written as the letter f.

Example 2

Input
num = 0
Output
"0"

The reading is nothing, which is written as a single zero rather than as no digits at all.

Example 3

Input
num = -2147483648
Output
"80000000"

Adding two raised to the thirty-second turns this reading into two raised to the thirty-first, which in base sixteen is an eight followed by seven zeros.

Constraints

  • -2^31 <= num <= 2^31 - 1

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def to_hex(num: int) -> str:
Java
public String toHex(int num)