-
Notifications
You must be signed in to change notification settings - Fork 0
/
convertaNumbertoHexadecimal*
54 lines (47 loc) · 1.83 KB
/
convertaNumbertoHexadecimal*
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/************************/
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.
/************************/
/*
要将一个十进制数转换为十六进制数,不管其是正数还是负数,都只需要将其二进制表示每四位分成一个单元,将其取出后计算这四位二进制数代表的十进制数,与0~f之间的数字做一个映射即可。要把每四位取出也很简单,与0xf进行AND运算即可。
在C++中,左移是逻辑移位,也就是说在数字后面补0,右移运算符是算术移位,也就是在左侧补符号位(正数补0,负数补1)
*/
/*
如果是负数,就直接强制转换为无符号数,直接补码变为无符号数。
正数的时候就是一个简单的十六进制转换问题。
*/
class Solution {
public:
string toHex(int num) {
/*string res;
vector<char>re{ '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
int low = 0, high = 0;
if (num == 0) {
return "0";
}
while (num&&res.size() < 8) {
res = re[(num & 0xf)] + res;
num = num >> 4;
}
return res;*/
if (num == 0) return "0";
string ans;
unsigned int n;
n = (unsigned int)num;
while (n > 0) {
int a = n % 16;
string c;
n /= 16;
if (a > 9)
c += 'a' + a - 10;
else
c += '0' + a;
ans.insert(0, c);
}
return ans;
}
};