405. Convert a Number to Hexadecimal
https://leetcode.com/problems/convert-a-number-to-hexadecimal/
/*
* @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