算法笔记: 力扣#405 数字转换为十六进制数

问题描述


解法


分析

Python 实现

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 实现

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;
}
}

时间复杂度

O(logN)

空间复杂度

O(1)

链接


405. Convert a Number to Hexadecimal
405. 数字转换为十六进制数
(English version) Algorithm Notes: Leetcode#405 Convert a Number to Hexadecimal