405. Convert a Number to Hexadecimal
Input:
26
Output:
"1a"Input:
-1
Output:
"ffffffff"Last updated
Input:
26
Output:
"1a"Input:
-1
Output:
"ffffffff"Last updated
string toHex(int num) { // time: O(1); space: O(1)
string hex = "0123456789abcdef";
if (num == 0) return "0";
string res;
while (num && res.length() < 8) {
res = hex[num & 0xf] + res;
num >>= 4;
}
return res;
}string toHex(int num) { // time: O(1); space: O(1)
string hex = "0123456789abcdef";
if (num == 0) return "0";
string res;
unsigned int n = num;
while (n) {
res = hex[n & 0xf] + res;
n >>= 4;
}
return res;
}