0%

convert-a-number-to-hexadecimal

Convert a Number to Hexadecimal – LeetCode 405

Problem

Description

Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
string toHex(int num) {
if(!num) return "0";
const char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
string s;
unsigned int n = num;
while(n > 0){
s = hex[n % 16] + s;
n /= 16;
}
return s;
}
};

思路

简单的转换负数然后进行进制转换。时间复杂度$O(log{n})$,空间复杂度$O(log{n})$。
耗时$4$ ms,排名$95.87\%$

Better

思路

还没看到更好的思路。