Given a 32-bit integer (signed or unsigned), convert it to its hexadecimal in lowercase. The result should not have leading zero unless it is equal to zero. Please do not use any inbuilt converting utility. This serves as a coding exercise for beginners.
The elegant solution is to first have a lookup table defined in a const string, and concatenate the remainder in the reverse order, as shown below:
That is: 10767 in decimal equals to 2*16^3 + 10*16^2 + 0*16^1 + 15*16^0.
If the input is zero, we then need to return ‘0’ instead of the empty string.
C++ source code to convert a number to hexadecimal
Given the above explanation, here is the quick C++ function that converts a signed/unsigned 32-bit integer to its Hexadecimal string representation.
class Solution {
public:
string toHex(int num) {
const string table = "0123456789abcdef"; // lookup hexadecimal
unsigned int x = num; // make negative complement
string r = "";
while (x > 0) {
int y = x % 16; // get remainder
r = table[y] + r; // concatenate in the reverse order
x /= 16;
}
return r == "" ? "0" : r;
}
};
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: How to Implement and Unit Test LineSpace Algorithm in C++?
Next Post: How to Implement The Sgn Function in C++?