您的位置:首页 > 其它

[Leetcode] 405. Convert a Number to Hexadecimal 解题报告

2017-09-22 16:50 387 查看
题目

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

Note:
All letters in hexadecimal (
a-f
) must be in lowercase.
The hexadecimal string must not contain extra leading 
0
s. 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.
The given number is guaranteed to fit within the range of a 32-bit signed integer.
You must not use any method provided by the library which converts/formats the number to hex directly.

Example 1:
Input:
26

Output:
"1a"


Example 2:
Input:
-1

Output:
"ffffffff"

思路

由于16是2的次幂,并且整数在计算机中都是以二进制的形式表示的,所以转化为16进制的方法非常简单:每次获得二进制的最低4位,直接将其转换为16进制的表示即可。在C++中实现需要注意的一点是:由于有符号整数和无符号整数在负数情况下的循环移位有所不同,所以我们在对num进行循环移位前,需要首先将其显式转换为无符号整数,这样可以统一处理正整数和负整数。

这道题目虽然也可以用传统的除余法解决,但是代码就相对复杂多了,而且处理补码的情况比较麻烦。

代码

class Solution {
public:
string toHex(int num) {
string ret("");
string hex_chars("0123456789abcdef");
while (num) {
ret.push_back(hex_chars[num & 0xF]);
num = (unsigned)num >> 4;
}
reverse(ret.begin(), ret.end());
return ret.empty() ? "0" : ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: