Convert a Number to Hexadecimal LeetCode solution in C++

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

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0