(1)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:
- 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 useany method provided by the library which converts/formats the number to hex directly.
分三类情况讨论,在讨论小于零的情况时,转化为大于零的整数来转换为十六进制数。
#include <string>
class Solution {
public:
string toHex(int num) {
char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
if(num==0)
return "0";
else if(num>0)
{
string res;
while(num>0)
{
int remind=num%16;
num=num/16;
if(remind<10)
{
char c = hex[remind];
res += c;
}
else
{
char c = hex[remind];
res += c;
}
}
reverse(res.begin(),res.end());
return res;
}
else if(num<0)
{
string res;
num=(-1)*num-1;
while(num>0)
{
int remind=num%16;
char c = remind+'0';
if(remind<10)
{
char c = hex[15-remind];
res += c;
}
else
{
char c = hex[15-remind];
res += c;
}
num/=16;
}
for(int j=res.size();j<8;j++)
res.push_back('f');
reverse(res.begin(),res.end());
return res;
}
}
};