Difficulty: Easy | Acceptance: 54.00% | Paid: No Topics: Math, String, Bit Manipulation
Given an integer num, return a string representing its hexadecimal representation. For negative integers, use two’s complement method.
All the letters in the answer should be lowercase, and there should be no leading zeros in the answer unless the number is 0. If the number is zero, it is represented by a single zero character ‘0’; otherwise, the first character in the string is not the zero character.
The given number is guaranteed to fit within the range of a 32-bit signed integer.
- Examples
- Constraints
- Bit Manipulation
- Built-in Functions
Examples
Input: num = 26
Output: "1a"
Input: num = -1
Output: "ffffffff"
Constraints
- -2^31 <= num <= 2^31 - 1
Bit Manipulation
Intuition Hexadecimal is base 16, which corresponds to 4 bits in binary. We can extract the number 4 bits at a time and map it to the corresponding hex character.
Steps
- Handle the edge case where
numis 0. - Create a mapping array or string for hex characters “0123456789abcdef”.
- Loop 8 times (since 32 bits / 4 bits = 8 hex digits).
- In each iteration, mask the last 4 bits using
num & 0xfto get the value. - Prepend the corresponding hex character to the result.
- Unsigned right shift
numby 4 bits to process the next nibble. - Remove leading zeros from the result.
class Solution:
def toHex(self, num: int) -> str:
if num == 0:
return "0"
hex_map = "0123456789abcdef"
res = []
for _ in range(8):
res.append(hex_map[num & 0xf])
num >>= 4
return "".join(reversed(res))Complexity
- Time: O(1) - We iterate a constant number of times (8).
- Space: O(1) - Excluding the space required for the output string.
- Notes: This is the most efficient algorithmic approach.
Built-in Functions
Intuition Most programming languages provide standard library functions to convert integers to hexadecimal strings, often handling two’s complement for negative numbers automatically.
Steps
- Identify the built-in method for the target language (e.g.,
hex(),toString(16),Integer.toHexString). - Call the method with the input number.
- Return the result.
class Solution:
def toHex(self, num: int) -> str:
return hex(num & 0xffffffff)[2:]Complexity
- Time: O(1) - Depends on implementation, but generally constant for fixed-width integers.
- Space: O(1) - Excluding the space required for the output string.
- Notes: This is the most concise approach but may not be allowed in interviews testing algorithmic knowledge.