Convert a Number to Hexadecimal

Given a 32-bit integer `num`, return its hexadecimal representation as a string of lowercase digits with no leading zeros (except for the number 0 itself, which is `"0"`). Negative numbers use two's complement, so -1 becomes `"ffffffff"`. Do not use a built-in conversion function.

30:00

Convert a Number to Hexadecimal
easy
Free written solution
Topics
Companies

Given a 32-bit integer num, return its hexadecimal representation as a string of lowercase digits with no leading zeros (except for the number 0 itself, which is "0"). Negative numbers use two's complement, so -1 becomes "ffffffff". Do not use a built-in conversion function.

Example 1:
Input: {"num":26}
Output: 1a
Constraints:
  • −231≤num≤231−1-2^{31} \leq \text{num} \leq 2^{31} - 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"num":26}

num = 26. One hex digit holds exactly 4 bits, so we can read the answer off the 32-bit pattern one nibble at a time.

num = 26

32 bits, 8 nibbles

0
0
0
0

?

0
0
0
0

?

0
0
0
0

?

0
0
0
0

?

0
0
0
0

?

0
0
0
0

?

0
0
0
1

?

1
0
1
0

?

each box is one nibble = one hex digit

digits lookup: value → character

0

0

1

1

2

2

3

3

4

4

5

5

6

6

7

7

8

8

9

9

10

a

11

b

12

c

13

d

14

e

15

f

answer, built right to left

Variables
VariableValue
num26
DepthFunction Call
Stack empty
0/10