Convert a Number to Hexadecimal LeetCode solution in Python

1
# Runtime: 33 ms (Top 88.95%) | Memory: 13.8 MB (Top 62.28%)
2
class Solution:
3
def toHex(self, num: int) -> str:
4
ret = [
5
"0",
6
"1",
7
"2",
8
"3",
9
"4",
10
"5",
11
"6",
12
"7",
13
"8",
14
"9",
15
"a",
16
"b",
17
"c",
18
"d",
19
"e",
20
"f",
21
]
22
ans = ""
23

24
if num < 0:
25
num = pow(2, 32) + num
26

27
if num == 0:
28
return "0"
29
while num > 0:
30
ans = ret[num % 16] + ans
31
num = num // 16
32

33
return ans

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0