[LeetCode]405. Convert a Number to Hexadecimal
题目描述
思路
位运算,每次获取4位,转化为对应的16进制数
因为题目说不会超过32位int并且负数用补码,那可以加入位置计数器,32位二进制表示成十六进制是8位
代码
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
string toHex(int num) {
if (num == 0)
return "0";
string hex = "0123456789abcdef", res = "";
int count = 0;
while (num && count < 8) {
res = hex[num & 0xf] + res;
num >>= 4;
++count;
}
return res;
}
};
int main() {
Solution s;
cout << s.toHex(-1) << endl;
system("pause");
return 0;
}
276



被折叠的 条评论
为什么被折叠?



