[LeetCode]405. Convert a Number to Hexadecimal

来源:互联网 发布:摄影网络销售技巧 编辑:程序博客网 时间:2024/05/16 17:34

[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;}
0 0