Convert a Number to Hexadecimal solution and explanation
9 more videos on this problem
405. Convert a Number to Hexadecimal | LEETCODE EASYcode Explainer · 4:42 · 8K views
Convert A Number To Hexadecimal | Leetcode Python Solution | PythonPython Guruji · 15:09 · 4K views
Leetcode 405. Convert a Number to HexadecimalLeetcode题解 · 9:54 · 2K views
405. Convert a Number to Hexadecimal | Leetcode | PythonAbdullah Arshed · 4:24 · 1K views
Convert a Number to Hexadecimal | Leetcode 405 | Approach + Code with explanation.Pirai's Academy · 9:14 · 1K views
小旭讲解 LeetCode 405. Convert a Number to Hexadecimal 位运算 - EP15HU Xiaoxu · 5:39 · 1K views
LeetCode 405 | Convert a Number to Hexadecimal | Bits Manipulation | Debug | JavaSleepy Cracker · 6:04 · 971 views
Convert a Number to Hexadecimal (Leetcode 405) in TeluguCoding Interview Preparation · 4:51 · 510 views
405. Convert a Number to Hexadecimal (Leetcode Easy)Programming Live with Larry · 11:29 · 459 views
Convert a Number to Hexadecimal #leetcode #csharp #easyWinEi · 6:13 · 403 views
The problem
Given a 32-bit integer num, return a string representing its hexadecimal representation. For negative integers, 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.
Example 1:
Input: num = 26 Output: "1a"
Example 2:
Input: num = -1 Output: "ffffffff"
Constraints:
-231 <= num <= 231 - 1
Approach overview
Problem Overview: Convert a signed 32-bit integer into its hexadecimal string representation without using built-in conversion utilities. For negative numbers, the result must follow the two's complement representation used by computers.
Approach 1: Bitwise Iteration Method (O(1) time, O(1) space)
This approach works directly with bit manipulation. A hexadecimal digit represents exactly 4 bits, so you can repeatedly extract the last 4 bits of the number using a bitmask 0xf. The operation num & 0xf isolates the lowest hex digit. Convert that value (0–15) to its corresponding character (0–9 or a–f), append it to the result, then shift the number right by 4 bits using num >>> 4 (unsigned shift in languages that support it). This continues until the number becomes zero or up to 8 hex digits are processed for a 32‑bit integer. The key insight is that masking and shifting mimic how hexadecimal is stored at the binary level, making the conversion extremely efficient. Since a 32‑bit integer produces at most 8 hex digits, the runtime is effectively constant. This method is preferred in interviews because it demonstrates strong understanding of bit operations and two's complement representation.
Approach 2: Divide and Conquer Method – Recursive (O(log16 n) time, O(log16 n) space)
This approach uses classic base conversion from math. Divide the number by 16 to reduce the problem size, then recursively process the quotient until the base case is reached. Each recursion step handles one hexadecimal digit by computing num % 16, mapping the remainder to its hex character. The recursive call builds the higher‑order digits first, and the remainder contributes the current digit. Because each step divides the number by 16, the recursion depth equals the number of hex digits, which is O(log16 n). This version is easier to reason about conceptually because it mirrors the mathematical definition of base conversion. However, it requires careful handling of negative numbers to preserve the correct two's complement representation, and recursion introduces additional stack space.
Recommended for interviews: The bitwise iteration method is what most interviewers expect. It shows you understand how hexadecimal aligns with binary (4 bits per digit) and how masking and shifting extract values efficiently. The recursive divide‑by‑16 approach demonstrates the general base‑conversion idea and is useful for explaining the concept first, but the iterative bitwise solution better showcases practical knowledge of bit manipulation and low‑level number representation.
Approach 1: Bitwise Iteration Method
This approach involves translating a number to hexadecimal by processing 4 bits at a time, which directly convert to a single hexadecimal character. We iterate over the integer, extracting these 4 bits using bit masking and shifts, and convert each to its corresponding hexadecimal character. By adhering to these operations iteratively and concatenating the results, we build the hexadecimal representation of the entire number.
def toHex(num: int) -> str:
if num == 0:
return "0"
hex_chars = "0123456789abcdef"
result = []
n = num & 0xFFFFFFFF
while n:
result.append(hex_chars[n & 0xf])
n >>= 4
return ''.join(reversed(result))
print(toHex(26)) # Output: "1a"
print(toHex(-1)) # Output: "ffffffff"public class HexConverter {
public static String toHex(int num) {
char[] hexChars = "0123456789abcdef".toCharArray();
StringBuilder hexString = new StringBuilder();
long n = num & 0xFFFFFFFFL; // Use long to deal with negative numbers
if (n == 0) return "0";
while (n > 0) {
hexString.insert(0, hexChars[(int)(n & 0xf)]);
n >>= 4;
}
return hexString.toString();
}
public static void main(String[] args) {
System.out.println(toHex(26)); // Output: "1a"
System.out.println(toHex(-1)); // Output: "ffffffff"
}
}#include <string>
#include <iostream>
std::string toHex(int num) {
std::string hex = "0123456789abcdef";
std::string result = "";
unsigned int n = (unsigned int)num;
do {
result = hex[n & 0xf] + result;
n >>= 4;
} while (n);
return result;
}
int main() {
std::cout << toHex(26) << std::endl; // Output: "1a"
std::cout << toHex(-1) << std::endl; // Output: "ffffffff"
return 0;
}function toHex(num) {
const hexChars = "0123456789abcdef";
if (num === 0) return "0";
let result = "";
let n = num >>> 0; // Convert to unsigned
while (n !== 0) {
result = hexChars[n & 0xf] + result;
n >>>= 4;
}
return result;
}
console.log(toHex(26)); // Output: "1a"
console.log(toHex(-1)); // Output: "ffffffff";#include <stdio.h>
char* toHex(int num) {
static char hex[] = {"0123456789abcdef"};
static char buffer[9];
int i = 8;
unsigned int n = (unsigned int)num;
buffer[i] = '\0';
do {
buffer[--i] = hex[n & 0xf];
n >>= 4;
} while (n);
return &buffer[i];
}
int main() {
printf("%s\n", toHex(26)); // Output: "1a"
printf("%s\n", toHex(-1)); // Output: "ffffffff"
return 0;
}using System;
class HexConverter {
public static string ToHex(int num) {
string hexChars = "0123456789abcdef";
if (num == 0) return "0";
string result = "";
uint n = (uint)num;
while (n != 0) {
int index = (int)(n & 0xf);
result = hexChars[index] + result;
n >>= 4;
}
return result;
}
static void Main() {
Console.WriteLine(ToHex(26)); // Output: "1a"
Console.WriteLine(ToHex(-1)); // Output: "ffffffff"
}
}This Python implementation utilizes a list to accumulate hexadecimal digits derived from bit masked segments. The number is handled as unsigned to ensure proper conversion of negatives into their correct complementary forms.
Time Complexity: O(1) — Processing a fixed number of 4-bit segments.
Space Complexity: O(1) — Output is static in size.
Approach 2: Divide and Conquer Method—Recursive
This method rephrases the iterative handling of bits by adopting a recursive approach to directly tackle the conversion of each 4-bit segment into its hexadecimal form. The number is cumulatively divided into smaller subproblems (sub-operations on lesser significant bits), each recursively addressed to construct the total solution's character set.
def helper(num):
if num == 0:
return ""
else:
return helper(num >> 4) + "0123456789abcdef"[num & 0xf]
def toHex(num: int) -> str:
if num == 0:
return "0"
return helper(num & 0xFFFFFFFF)
print(toHex(26)) # Output: "1a"
print(toHex(-1)) # Output: "ffffffff"public class HexConverter {
public static String helper(long num) {
if (num == 0) return "";
return helper(num >> 4) + "0123456789abcdef".charAt((int)(num & 0xf));
}
public static String toHex(int num) {
if (num == 0) return "0";
return helper(num & 0xFFFFFFFFL);
}
public static void main(String[] args) {
System.out.println(toHex(26)); // Output: "1a"
System.out.println(toHex(-1)); // Output: "ffffffff"
}
}#include <iostream>
#include <string>
std::string helper(unsigned int num) {
if (num == 0) return "";
return helper(num >> 4) + "0123456789abcdef"[num & 0xf];
}
std::string toHex(int num) {
if (num == 0) return "0";
return helper((unsigned int)num);
}
int main() {
std::cout << toHex(26) << std::endl; // Output: "1a"
std::cout << toHex(-1) << std::endl; // Output: "ffffffff"
return 0;
}function helper(num) {
if (num === 0) return "";
return helper(num >>> 4) + "0123456789abcdef"[num & 0xf];
}
function toHex(num) {
if (num === 0) return "0";
return helper(num >>> 0);
}
console.log(toHex(26)); // Output: "1a"
console.log(toHex(-1)); // Output: "ffffffff";#include <stdio.h>
char hexDigits[] = "0123456789abcdef";
// Recursive function
void helper(unsigned int num, char *buffer, int *index) {
if (num == 0)
return;
helper(num >> 4, buffer, index);
buffer[(*index)++] = hexDigits[num & 0xf];
}
char* toHex(int num) {
static char buffer[9] = {0};
if (num == 0)
return "0";
int index = 0;
helper((unsigned int)num, buffer, &index);
buffer[index] = '\0';
return buffer;
}
int main() {
printf("%s\n", toHex(26)); // Output: "1a"
printf("%s\n", toHex(-1)); // Output: "ffffffff"
return 0;
}using System;
class HexConverter {
static string Helper(uint num) {
if (num == 0)
return "";
return Helper(num >> 4) + "0123456789abcdef"[(int)(num & 0xf)];
}
public static string ToHex(int num) {
if (num == 0) return "0";
return Helper((uint)num);
}
static void Main() {
Console.WriteLine(ToHex(26)); // Output: "1a"
Console.WriteLine(ToHex(-1)); // Output: "ffffffff"
}
}Python mirrors the recursive strategy via the direct conversion of smaller bit groups into characters, halting ultimately at zero processing each four bit segment upwards, progressively accumulating the representation backwards as function calls evaluate in stack reversal manner.
Time Complexity: O(1) — Processing bound by the inherent constraint on cycle execution on 32 bits.
Space Complexity: O(1) — Space allocated effectively tied to function calls, inherently limited by stack constraints.
Approach 3: Default Approach
func toHex(num int) string {
if num == 0 {
return "0"
}
sb := &strings.Builder{}
for i := 7; i >= 0; i-- {
x := num >> (4 * i) & 0xf
if x > 0 || sb.Len() > 0 {
var c byte
if x < 10 {
c = '0' + byte(x)
} else {
c = 'a' + byte(x-10)
}
sb.WriteByte(c)
}
}
return sb.String()
}Complexity comparison
| Approach | Complexity |
|---|---|
| Bitwise Iteration Method | Time Complexity: O(1) — Processing a fixed number of 4-bit segments. |
| Divide and Conquer Method—Recursive | Time Complexity: O(1) — Processing bound by the inherent constraint on cycle execution on 32 bits. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Bitwise Iteration Method | O(1) | O(1) | Best general solution. Efficient for fixed-size integers and demonstrates bit manipulation knowledge. |
| Divide and Conquer (Recursive) | O(log16 n) | O(log16 n) | Useful for explaining base conversion conceptually or when recursion is preferred. |
Frequently asked questions
Is Convert a Number to Hexadecimal easy or hard?
Convert a Number to Hexadecimal is categorized as an Easy problem. The main challenge is understanding how hexadecimal digits correspond to 4-bit binary groups and handling negative numbers using two's complement representation.
Convert a Number to Hexadecimal Python/Java solution
Python, Java, C++, C#, JavaScript, and C implementations typically use a loop with bit masking and right shifts. Extract the last 4 bits using num & 0xf, map it to a hexadecimal character, append to the result, then shift the number right by 4 bits.
How to solve Convert a Number to Hexadecimal in O(1)?
Use bit manipulation with a 4-bit mask. Extract the lowest hexadecimal digit using num & 0xf, convert it to the corresponding character, then shift the number right by 4 bits. Repeat until the number becomes zero or up to 8 iterations for a 32-bit integer.
What is the best approach for Convert a Number to Hexadecimal?
The bitwise iteration method is the most efficient and commonly expected solution. It extracts hexadecimal digits using a mask (num & 0xf) and shifts the number right by 4 bits each step. Since a 32-bit integer produces at most 8 hex digits, the algorithm runs in O(1) time and constant space.
Is Convert a Number to Hexadecimal asked at Google/Amazon/Meta?
Bit manipulation and number representation problems like this appear in interviews at companies such as Amazon, Google, and Meta. They test understanding of binary operations, masking, and two's complement representation rather than relying on built-in conversion utilities.
What data structure is used in Convert a Number to Hexadecimal?
The solution primarily relies on bit manipulation rather than complex data structures. Most implementations use a simple character array or string builder to map values 0–15 to hexadecimal characters (0–9 and a–f).
What is the time complexity of Convert a Number to Hexadecimal?
The optimal bitwise approach runs in O(1) time because a 32-bit integer generates at most 8 hexadecimal digits. A mathematical divide-by-16 approach takes O(log16 n) time since the number shrinks by a factor of 16 at each step.
