Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
Note:
Example 1:
Input:
26
Output:
"1a"
Example 2:
Input:
-1
Output:
"ffffffff"
class Solution {
public:
std::string toHex(unsigned int num) {
if(num == 0) {
return std::string{"0"};
}
std::string res{};
while(num != 0) {
auto tmp = num & 0xf;
if(tmp >= 10) {
res += 'a' + tmp - 10;
} else {
res += '0' + tmp;
}
num >>= 4;
}
std::reverse(res.begin(), res.end());
return res;
}
};