algorithm notes: leetcode#405 convert a number to hexadecimal

Problem


Solution


Initial thoughts

Python implementation

1
2
3
4
5
6
7
8
9
10
11
12
class :
def toHex(self, num):
if 0 <= num < 10:
return str(num)
if num < 0:
num = num + 2**32
chars = [str(i) if i < 10 else chr(i-10+ord('a')) for i in range(16)]
res = []
while num:
res.append(chars[num&15])
num >>= 4
return "".join(res[::-1])

Java implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class {
public String toHex(int num) {
if(num >= 0 && num < 10){
return Integer.toString(num);
}
char[] map = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
String res = "";
while(num != 0){
res = map[num & 15] + res;
num >>>= 4;
}
return res;
}
}

Time complexity

O(logN)

Space complexity

O(1)


405. Convert a Number to Hexadecimal
(中文版) 算法笔记: 力扣#405 数字转换为十六进制数