LeetCode OJ 405. Convert a Number to Hexadecimal
Description
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 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.
- 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.
Example1
Input:
26Output:
“1a”
Example2
Input:
-1Output:
“ffffffff”
解题思路
首先想到的处理方法就是对数进行位操作(bit manipulation)。要转换为16进制数,那么每次处理的就是低位的4bit,要取到低位的4bit可以用&操作得到,然后对取到的数进行判断,从而转换为‘0’~‘9’字符或‘a’~‘f’字符加入到结果字符串的末尾,然后将原来的数字右移四位。执行循环,直到正数变为0或者负数显示到32bit。
Note:
负数在计算机内部采用2的补码形式来存储,就是每一个二进制位都取反,得到的结果再加1。这样我们在处理负数时直接右移4bit时就可以了。(其实一开始也没注意到这一点,所以一开始是将负数转换为正数进行处理,后来才想起来计算机中负数的存储方式。)但是我们需要做一个限制:32bit,不然会产生死循环。
代码
class Solution {
public:
string toHex(int num) {
if(num == 0)
return "0";
string ans = "";
int bit = 8;
while (num && bit) {
int tmp = num & 15;
if (tmp < 10)
ans = to_string(tmp) + ans;
else
ans = (char)('a' + tmp - 10) + ans;
num = num >> 4;
bit--;
}
return ans;
}
};