[leetcode] 405. Convert a Number to Hexadecimal

https://leetcode.com/contest/6/problems/convert-a-number-to-hexadecimal/

分析:10进制转换成16进制,不能用库函数,刚开始,我被误导,一直到考虑负数怎么表示成补码,其实,这个系统已经帮我们做好了,计算机里面就是二进制补码表示的,我们需要做的,就是把数字表示成32位二进制,然后每四位映射成一个16进制数字,最后去掉前导0,然后就ok。

注意:不要被什么正数,负数,0,如何表示成二进制补码吸引注意力。

 1 string toHex(int num) {
 2     string res = "";
 3     for (int i = 0; i < 8; i++){
 4         res.append(1, "0123456789abcdef"[num & 15]);
 5         num >>= 4;
 6     }
 7     reverse(res.begin(), res.end());
 8     while(res.size() > 1 && res[0] == '0')
 9         res = res.substr(1);
10     return res;
11 }
 1  string s[] = {"0000", "0001","0010", "0011",
 2                 "0100", "0101","0110", "0111",
 3                 "1000", "1001","1010", "1011",
 4                 "1100", "1101","1110", "1111"
 5                 };
 6 char ch[] = {'0','1','2','3',
 7             '4','5','6','7',
 8             '8','9','a','b',
 9             'c','d','e','f'
10             };
11 class Solution {
12 public:
13 
14  string toHex(int num) {
15         if(num == 0) {
16             return "0";
17         }
18         if(num == 1) {
19             return "1";
20         }
21         if(num == INT_MIN) {
22             return "80000000";
23         }
24         string t = "";
25         for (int i = 31; i >= 0; i--) {
26             if(num & (1 << i)) t.append(1, '1');
27             else t.append(1, '0');
28         }
29         map<string , char> m;
30         for (int i = 0; i < 16; i++) {
31             m[s[i] ] = ch[i];
32         }
33         string res = "";
34         for (int i = 0; i < 32; i += 4) {
35             string td = t.substr(i, 4);
36             res.append(1, m[td]);
37         }
38         while(res.size() > 1 && res[0] == '0')
39             res = res.substr(1);
40         return res;
41     }
42 };
原文地址:https://www.cnblogs.com/y119777/p/5905564.html