> For the complete documentation index, see [llms.txt](https://hao-fu-1.gitbook.io/oj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hao-fu-1.gitbook.io/oj/math/jin-zhi-zhuan-huan/405.-convert-a-number-to-hexadecimal.md).

# 405. Convert a Number to Hexadecimal

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

整数表示成16进制字符串。整数本身就是用的二进制表达，转成16进制只要每4位做下映射。

参考自[这](https://link.zhihu.com/?target=https%3A//leetcode.com/problems/convert-a-number-to-hexadecimal/discuss/89238/Concise-C%252B%252B-Solution)。

```cpp
/*
 * @lc app=leetcode id=405 lang=cpp
 *
 * [405] Convert a Number to Hexadecimal
 */

// @lc code=start
class Solution {
public:
    string toHex(int num) {
        if (num == 0) return "0";
        const auto HEX = "0123456789abcdef";
        string res;
        int cnt = 0;
        while (num != 0 && cnt++ < 8) {
            res += HEX[num & 0xf]; 
            num >>= 4;
        }
        reverse(res.begin(), res.end());
        return res;
    }
};
// @lc code=end


```
