Problem 405

Abstract / Summary

Convert an integer to its hexadecimal representation using letters for digits above nine.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0405.py

class Solution:
    def toHex(self, num: int) -> str:
        if num == 0:
            return "0"

        if num < 0:
            num = (2**32) + num

        print(num)

        h = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" ]
        result = ""
        while num > 0:
            four = num & 15
            num >>= 4
            result = h[four] + result

        return result
18 lines | 439 bytes | submitted August 20, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (400k+ submissions).

Typical patterns to solve this problem:
  • Bit Manipulation
  • Math
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method toHex. Its purpose is to convert a signed 32-bit integer into its hexadecimal string representation without using built-in conversion utilities. The algorithm first normalizes negative inputs to their unsigned 32-bit two’s-complement form, then iteratively extracts four-bit groups (nibbles) from the least-significant side, maps each nibble to the corresponding hexadecimal character, and builds the final string in the correct order.

Key Steps

The conversion process can be broken down into distinct logical blocks, each reflected in a concise code fragment.

The method begins with a trivial zero check, returning the literal "0" when the input equals zero:

if num == 0:
    return "0"

When the input is negative, the code computes its unsigned 32-bit equivalent by adding the value to 2**32. This leverages the fact that Python integers have arbitrary precision, so the addition yields the correct wrap-around representation:

if num < 0:
    num = (2**32) + num

A debugging print statement outputs the intermediate unsigned value; this can be useful during development to verify the transformation of negative numbers.

The lookup table h holds the hexadecimal digit characters in order, enabling constant-time translation from a numeric nibble to its string form:

h = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
     "a", "b", "c", "d", "e", "f"]

The core loop repeatedly isolates the lowest four bits of num using a bitwise AND with 0b1111 (decimal 15). The isolated nibble is used as an index into h, and the resulting character is prepended to the accumulating result string. After each iteration, num is shifted right by four bits, discarding the processed nibble:

result = ""
while num > 0:
    four = num & 15          # extract lowest nibble
    num >>= 4                # shift right by one nibble
    result = h[four] + result

When the loop terminates, result contains the full hexadecimal representation, which is then returned:

return result

Edge Cases

The implementation explicitly handles the case where the input is zero, returning "0" without entering the main loop. This avoids an empty result string that would otherwise be produced by the while-loop condition.

Negative numbers are transformed into their unsigned 32-bit two’s-complement equivalents. By adding 2**32 to a negative value, the code maps the range [-2**31, -1] onto [2**31, 2**32-1]. Consequently, the subsequent nibble extraction works uniformly for both originally positive and transformed negative values.

The loop condition while num > 0 ensures that leading zero nibbles are not emitted. For example, an input of 16 (binary 0b10000) yields a single iteration that extracts the low nibble 0 and then the next iteration extracts 1, producing "10" rather than "010".

Performance Optimizations

The algorithm operates directly on integer bit patterns, avoiding any string parsing or high-level conversion functions. The use of a pre-allocated list h for digit lookup provides O(1) access for each nibble, eliminating the need for conditional branches or arithmetic to compute character codes.

Bitwise operations (& and >>) are executed in constant time on native integer types, making each iteration lightweight. Because the loop processes exactly one nibble per iteration, the number of iterations is bounded by the fixed width of a 32-bit integer (at most eight cycles). This deterministic bound ensures that the method runs in a predictable amount of time regardless of the input magnitude.

Prepending characters to the result string (result = h[four] + result) builds the final output without requiring a separate reversal step. Although string concatenation can be costly in some languages, the maximum number of concatenations is limited to eight, keeping the overhead negligible.

written by openai gpt

ELI5 - Simplified Explanation

Think of this code like a translator that turns regular numbers into a special secret code called hexadecimal. Usually, we count using ten digits, but this code uses sixteen characters, adding letters from a up to f to the normal numbers.

The first step checks if the number is zero, because zero stays zero in every language. If the number is negative, the code adds a very big number to it to change how it looks while keeping its value the same for this special system.

The part labeled h is like a toolbox containing all the sixteen characters needed to build the secret code. A loop then starts to take the number apart in small pieces. Each piece represents four bits of information at a time. The code looks at the last four bits, finds the matching character from the toolbox, and puts that character at the front of the final answer. After taking each piece, the original number gets smaller until there is nothing left to process, leaving behind a finished code made of numbers and letters.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.58 | σ = 1.21

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
lzl124631x C++
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
lzl124631x C++
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
yuanliu666 Kotlin
zfang399 C++
39 links | 27 authors | 11 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 easy 2 medium
5 solutions   August 20, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality