Convert a Number to Hexadecimal LeetCode solution in C++
1class Solution {2public:3string toHex(int num) {4string hex = "0123456789abcdef";5unsigned int n = num; // to handle neg numbers6string ans = "";7if (n == 0) return "0";8while (n > 0) {9int k = n % 16;10ans += hex[k];11n /= 16;12}13reverse(ans.begin(), ans.end()); // as we stored it in the opposite order14return ans;15}16};