Convert a Number to Hexadecimal

405.Convert a Number to Hexadecimal

Given an integer num, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.

All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.

Note: You are not allowed to use any built-in library method to directly solve this problem.

Example 1:

1
2
Input: num = 26
Output: "1a"

Example 2:

1
2
Input: num = -1
Output: "ffffffff"

时间复杂度:O(n)

空间复杂度:O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
string toHex(int num ) {
string pos = "0123456789abcdef";
if (num == 0)
{
return "0";
}
string ans;

unsigned _num = num;
while (_num)
{
ans += pos[_num % 16];
_num = _num / 16;
}
reverse(ans.begin(), ans.end());
return ans;
}
};

位运算:

时间复杂度:O(k),k是整数的十六进制数的位数

空间复杂度:O(k)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
string toHex(int num) {
if (num == 0) {
return "0";
}
string sb;
for (int i = 7; i >= 0; i --) {
int val = (num >> (4 * i)) & 0xf;
if (sb.length() > 0 || val > 0) {
char digit = val < 10 ? (char) ('0' + val) : (char) ('a' + val - 10);
sb.push_back(digit);
}
}
return sb;
}
};