[
math
bit manipulation
]
Leetcode 0405 Convert a Number to Hexadecimal
Problem statement
https://leetcode.com/problems/convert-a-number-to-hexadecimal/
Solution
If number is positive, we use mod 16
to evaluate the last symbol, then divide number by 16
and continue until we converge. Actually the same logic will work for negative numbers as well: for example for num = -100
, we have ffffff9c
, because -100 mod 16 = 12
, -100 // 16 = 7
, then -7 mod 16 = 9
, -7 // 16 = -1
. When we reached -1
all the rest symbols will be f
, and we need just take such that we have string of length 8
in the end.
Complexity
Time and space complexity is O(8)
.
Code
class Solution:
def toHex(self, num):
ans = ""
for i in range(8):
num, digit = divmod(num, 16)
ans += str(digit) if digit < 10 else chr(ord("a") + digit - 10)
return ans[::-1].lstrip("0") if ans != "0"*8 else "0"