Convert a Number to Hexadecimal
Problem Descriptionβ
Given an integer num
, return a string representing its hexadecimal representation. For negative integers, the 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.
Examplesβ
Example 1:
Input: num = 26
Output: "1a"
Example 2:
Input: num = -1
Output: "ffffffff"
Constraintsβ
-2^31 <= num <= 2^31 - 1
Solution for Convert Integer to Hexadecimal Problemβ
Approach: Bit Manipulationβ
To solve this problem, we convert the integer to its hexadecimal representation by handling one nibble (4 bits) at a time. For negative numbers, the twoβs complement is used.
Brute Force Approachβ
-
Convert Positive Numbers:
- Use a loop to repeatedly divide the number by 16, and record the remainder.
- Use a map to convert the remainder to a hexadecimal character.
- Concatenate the characters in reverse order to get the final hexadecimal string.
-
Handle Negative Numbers:
- Convert the number to its two's complement representation by adding (2^32) to the negative number.
- Apply the same method as for positive numbers.
Optimized Approachβ
- Since we are only dealing with 32 bits, we can use a mask to extract each nibble and convert it to a hexadecimal digit.
Code in Different Languagesβ
- C++
- Java
- Python
#include <string>
class Solution {
public:
std::string toHex(int num) {
if (num == 0) return "0";
unsigned int n = num;
std::string hex_chars = "0123456789abcdef";
std::string hex = "";
while (n) {
hex = hex_chars[n & 15] + hex;
n >>= 4;
}
return hex;
}
};
class Solution {
public String toHex(int num) {
if (num == 0) return "0";
long n = num & 0xFFFFFFFFL;
StringBuilder hex = new StringBuilder();
String hexChars = "0123456789abcdef";
while (n != 0) {
hex.insert(0, hexChars.charAt((int)(n & 15)));
n >>>= 4;
}
return hex.toString();
}
}
class Solution:
def toHex(self, num: int) -> str:
if num == 0:
return "0"
num &= 0xFFFFFFFF # handle negative numbers
hex_chars = "0123456789abcdef"
result = []
while num:
result.append(hex_chars[num & 15])
num >>= 4
return ''.join(result[::-1])
Complexity Analysisβ
- Time Complexity: because the maximum number of iterations is fixed (8 for 32-bit integers).
- Space Complexity: as the space required does not depend on the input size.
Authors:
Loading...