Convert a Number to Hexadecimal
Problem
Given an integer num
, return a string representing its hexadecimal representation. For negative integers, two’s complement method is used.
All the letters in the answer string should be lowercase characters, and there should not be any leading zeros in the answer except for the zero itself.
Note: You are not allowed to use any built-in library method to directly solve this problem.
Constraints
-231 <= num <= 231 - 1
Solution
The problem Convert a Number to Hexadecimal
can be solved by converting every 4 bits into a hexadecimal format.
Implementation
class Solution
{
public:
string toHex(int num)
{
char hashmap[17] = "0123456789abcdef";
unsigned int unum = num;
string ret;
do
{
ret = hashmap[unum & 0xF] + ret;
} while ((unum = unum >> 4));
return ret;
}
};