LeetCode405 Convert a Number to Hexadecimal


描述

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

Note:

  1. All letters in hexadecimal (a-f) must be in lowercase.
  2. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
  3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
  4. You must not use any method provided by the library which converts/formats the number to hex directly.

样例

1
2
3
4
5
Input:
26

Output:
"1a"
1
2
3
4
5
Input:
-1

Output:
"ffffffff"

思路

求一个int类型整数的十六进制表示。

直接4位4位压缩表示即可。需要注意的是负数的情况,由于C++中>>运算是带符号右移,负数的符号位是1右移高位会补1…然而我们的判断终止条件是为0(补1的话是永远不可能移到0的…),因此要先把有符号数转成无符号数再处理。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
string toHex(int num) {
if (num == 0) return "0";
string ans;
unsigned int x = num, bit;
while (x != 0) {
bit = x & 0XF;
ans += bit > 9 ? bit - 10 + 'a' : bit + '0';
x >>= 4;
}
reverse(ans.begin(), ans.end());
return ans;
}
};