LeetCode/405. Convert a Number to Hexadecimal.md

54 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [405. Convert a Number to Hexadecimal](https://leetcode.com/problems/convert-a-number-to-hexadecimal/description/)
# 思路
将用补码(2's complement)表示的数转换成16进制数。
## 思路一
进制转换常规思路。
首先将补码表示的数看做是无符号的数然后再用常规的不断除以16的方法转换进制。
例如将十进制数25转换成16进制:
> 25 / 16 = 1···9
> 1 / 16 = 0···1
> 所以结果就是19
## 思路二
由于2进制转16进制刚好是4位为一组所以可考虑从低位起不断获取num的四位bit再将其转换成16进制。
例如将十进制数25转换成16进制:
> 25的32位二进制表示为`000..0011001`, 最低四位`1001`的16进制表示为9次第四位`0001`的16进制表示为1再高位就全是0了所以结果就是19.
获得num的低四位可以通过num和mask`0x0000000f`进行按位与操作实现。
# C++
## 思路一
``` C++
class Solution {
public:
string toHex(int num) {
if(num == 0) return "0";
string mp = "0123456789abcdef";
string res;
unsigned n = (unsigned)num;
while(n > 0){
res += mp[n % 16];
n /= 16;
}
reverse(res.begin(), res.end());
return res;
}
};
```
## 思路二
``` c++
class Solution {
public:
string toHex(int num) {
if(num == 0) return "0";
string mp = "0123456789abcdef";
string res;
while(num != 0){
res += mp[0x0000000f & num];
num >>= 4;
}
reverse(res.begin(), res.end());
return res;
}
};
```