Skip to main content

Convert a Number to Hexadecimal - Solution & Explanation

EasyMathBit Manipulation13 min readAsked at: Amazon, Microsoft, Meta +3
Practice this problem

Problem Statement

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.

The function toHex converts an integer to its hexadecimal representation. We use a buffer to store the hexadecimal characters. Starting from the least significant 4 bits, repeatedly mask and shift right by 4 to map the bits to their respective hexadecimal character, appending each to the buffer until the number is zero.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(1) — The number of bits is fixed (32 bits), and we process each group of 4 bits individually.
Space Complexity: O(1) — Constant space for storing the result string.

Try this approach in the editor →

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.

Here, recursion plays a key role. We recursively break down the integer, handling higher bits first before appending the current 4-bit chunk. The recursion unwinds in reverse, letting us progressively build the hex string in correct order. The recursive splitting of number and buffer accumulation allows us to manage the character order efficiently.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(1) - The recursion depth is finite and predetermined by the bit-length.
Space Complexity: O(1) - Despite recursive calls, space use remains bounded, limited by internal function call overheads.

Try this approach in the editor →

Approach 3: Default Approach

Code

Python

Java

C++

Go

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Bitwise Iteration Method

Time Complexity: O(1) — The number of bits is fixed (32 bits), and we process each group of 4 bits individually.
Space Complexity: O(1) — Constant space for storing the result string.

Divide and Conquer Method—Recursive

Time Complexity: O(1) - The recursion depth is finite and predetermined by the bit-length.
Space Complexity: O(1) - Despite recursive calls, space use remains bounded, limited by internal function call overheads.

Default Approach

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Bitwise Iteration MethodO(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.

Video Solution

405. Convert a Number to Hexadecimal | LEETCODE EASYcode Explainer8,862 views views

Watch 9 more video solutions →

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.

Ready to solve this problem?

Practice Convert a Number to Hexadecimal with our built-in code editor and test cases.

Practice on FleetCode