Leetcode 405. Convert a Number to Hexadecimal
The problem is to convert a given integer number to its hexadecimal representation. The hexadecimal numeral system is base-16, which uses sixteen symbols: 0-9 and a-f. For example, the hexadecimal representation of the decimal number 26 is “1a”.
You need to write a function toHex
that takes an integer as input and returns a string representing its hexadecimal value.
With these clarifications, we can proceed to the next section.
Handling Negatives: Since the input can be negative, we need to handle the two’s complement representation. For a 32-bit signed integer, this means treating negative numbers unsigned by masking with 0xFFFFFFFF
.
Hexadecimal Mapping: We need a map of digits to hexadecimal characters (0-9
to 0-9
and 10-15
to a-f
).
Conversion Process:
#include <string>
class Solution {
public:
std::string toHex(int num) {
if (num == 0) {
return "0";
}
const char hexDigits[] = "0123456789abcdef";
std::string hexStr;
// Process the number using two's complement for negative numbers
unsigned int n = static_cast<unsigned int>(num);
while (n != 0) {
int lastFourBits = n & 0xF;
hexStr += hexDigits[lastFourBits];
n >>= 4;
}
// The digits were added in reverse order
std::reverse(hexStr.begin(), hexStr.end());
return hexStr;
}
};
The time complexity of this solution is O(log(n)), where n is the absolute value of the input number. This is because the loop extracts 4 bits at a time and shifts the number right, effectively reducing it by a factor of 16 each iteration. For 32-bit integers, this loop will run at most 8 times (since 32/4 = 8).
This approach efficiently converts an integer to its hexadecimal representation, handling both positive and negative values correctly.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?