LeetCode Problem Workspace
Convert a Number to Hexadecimal
Convert a 32-bit integer to its hexadecimal string using math operations and careful string manipulation techniques.
3
Topics
4
Code langs
3
Related
Practice Focus
Easy · Math plus String
Answer-first summary
Convert a 32-bit integer to its hexadecimal string using math operations and careful string manipulation techniques.
Ace coding interviews with Interview AiBoxInterview AiBox guidance for Math plus String
To solve Convert a Number to Hexadecimal, iterate using modulus and bit shifts to extract each hex digit, then build the string in correct order. Handle negative numbers using two's complement representation. This method avoids built-in conversion functions, ensuring understanding of low-level math and string handling in bit manipulation problems.
Problem Statement
Given a 32-bit signed integer, return its hexadecimal string representation. For negative integers, compute the two's complement and then represent the result in lowercase hexadecimal without leading zeros except for zero itself.
You are not allowed to use any built-in library functions that perform direct number-to-hexadecimal conversion. Ensure that your solution uses math operations, bit manipulation, and string construction to produce the correct output.
Examples
Example 1
Input: num = 26
Output: "1a"
Example details omitted.
Example 2
Input: num = -1
Output: "ffffffff"
Example details omitted.
Constraints
- -231 <= num <= 231 - 1
Solution Approach
Iterative Modulus Extraction
Repeatedly divide the absolute value of the number by 16, taking the remainder each time to determine the corresponding hexadecimal digit. Prepend each digit to a string until the number reduces to zero.
Two's Complement for Negatives
For negative numbers, first convert the number to its 32-bit two's complement representation. Then apply the same modulus extraction method to generate the hexadecimal string.
Mapping Values to Characters
Maintain a lookup array for values 0-15 mapped to '0'-'f'. Use this mapping to translate each numeric remainder into the correct hexadecimal character, ensuring lowercase output.
Complexity Analysis
| Metric | Value |
|---|---|
| Time | Depends on the final approach |
| Space | Depends on the final approach |
Time complexity is O(log16 N) because each division reduces the number by a factor of 16. Space complexity is O(1) for calculation plus O(log16 N) for the string result.
What Interviewers Usually Probe
- Check if the candidate correctly handles negative integers with two's complement conversion.
- Listen for explicit use of modulus and division or bit manipulation rather than built-in conversion functions.
- Verify that the string is built in the correct order and uses lowercase characters without extra leading zeros.
Common Pitfalls or Variants
Common pitfalls
- Forgetting to handle negative numbers using two's complement, leading to incorrect outputs.
- Appending digits instead of prepending, which reverses the hexadecimal string.
- Using uppercase letters or including leading zeros incorrectly.
Follow-up variants
- Convert a number to octal representation using similar math and string techniques.
- Support 64-bit integers while preserving two's complement handling and correct string formatting.
- Return the hexadecimal representation with a fixed width of 8 characters, padding with zeros as needed.
FAQ
How do I handle negative numbers in Convert a Number to Hexadecimal?
Convert the negative number to its 32-bit two's complement, then apply the same iterative modulus method to generate the hexadecimal string.
Can I use built-in functions like hex() or format()?
No, this problem explicitly forbids built-in conversion functions to test understanding of math and string operations.
Why does the output need to be lowercase?
The problem specifies lowercase letters for consistency and to ensure the correct format in interview evaluation.
What is the time complexity of the conversion?
Each division reduces the number by a factor of 16, giving O(log16 N) time complexity for the conversion loop.
How does the Math plus String pattern apply here?
You repeatedly use division and modulus to compute digits (Math) and then build the string in order (String), directly reflecting this pattern.
Solution
Solution 1
#### Python3
class Solution:
def toHex(self, num: int) -> str:
if num == 0:
return '0'
chars = '0123456789abcdef'
s = []
for i in range(7, -1, -1):
x = (num >> (4 * i)) & 0xF
if s or x != 0:
s.append(chars[x])
return ''.join(s)Solution 2
#### Java
class Solution:
def toHex(self, num: int) -> str:
if num == 0:
return '0'
chars = '0123456789abcdef'
s = []
for i in range(7, -1, -1):
x = (num >> (4 * i)) & 0xF
if s or x != 0:
s.append(chars[x])
return ''.join(s)Continue Practicing
Continue Topic
math
Practice more edge cases under the same topic.
arrow_forwardauto_awesomeContinue Pattern
Math plus String
Expand the same solving frame across more problems.
arrow_forwardsignal_cellular_altSame Difficulty Track
Easy
Stay on this level to stabilize interview delivery.
arrow_forward