405. Convert a Number to Hexadecimal

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

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

参考自

/*
 * @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

Last updated