Leetcode 405. Convert a Number to Hexadecimal

Problem Description

The problem is to convert a given 32-bit signed integer to hexadecimal. In case of negative integers, we need to use the two’s complement method. Note that we shouldn't have leading zeroes in the hexadecimal value and for zero, it is represented by a single zero character '0'. Also, the hexadecimal digits like 'a' to 'f' must be in lowercase.

Let's examine example,

Example :

Input: -1

Output: "ffffffff"

Approach:

In the given problem, we need to convert the given number into hexadecimal without using any built-in libraries. We can achieve this by bitwise shifting and bitwise AND operations. The idea is to get the last 4 bits of the number (num & 0xf) and map it to the corresponding hexadecimal digit. We map using a look-up vector which stores all hexadecimal digits from '0' to 'f'. Then, we right shift the original number by 4 bits (num >>= 4) to process the next four bits. This approach continues until all the bits in the original number are processed. Finally, we reverse the obtained string before returning the result.

Python solution

1
2python
3class Solution:
4    def toHex(self, num: int) -> str:
5        if num == 0:
6            return "0"
7            
8        hex_lst = "0123456789abcdef"
9        res = ""
10        for _ in range(8):
11            res = hex_lst[num & 0xf] + res
12            num >>= 4
13            if num == 0:
14                return res
15        return res

Here, the hex_lst variable stores all the hexadecimal digits. hex_lst[num & 0xf] is used to find the corresponding hexadecimal digit for the last four bits of the number. In the end, we return the hexadecimal representation of the number.

Java Solution

1
2java
3class Solution {
4    public String toHex(int num) {
5        if(num == 0){
6            return "0";
7        }
8        
9        char[] hex = "0123456789abcdef".toCharArray();
10        StringBuilder sb = new StringBuilder();
11        while(num != 0){
12            sb.append(hex[num & 0xf]);
13            num = num >>> 4;
14        }
15        
16        return sb.reverse().toString();
17    }
18}

This Java solution works in the same way as the Python solution. We create a character array that stores all the hexadecimal digits, and we reverse the string before returning the result.

Javascript Solution

1
2
3var toHex = function(num) {
4    if(num==0) return '0';
5    let hex = '0123456789abcdef', ans = '';
6    while(num!=0 && ans.length<8){
7        ans = hex[num & 0xf] + ans;
8        num = num >> 4;
9    }
10    return ans;
11};

This JavaScript function uses a similar approach to the Python and Java solutions to achieve the result.

C++ Solution

1
2cpp
3class Solution {
4public:
5    string toHex(int num) {
6        if(num==0)
7            return "0";
8        string hexadecimal = "0123456789abcdef";
9        string result = "";
10        int count = 0;
11        while(num!=0 && count++<8){
12            result = hexadecimal[num & 0xf] + result;
13            num = num >> 4;
14        }
15        return result;
16    }
17};

This C++ function also follows the same approach as previous functions to achieve the result.

C# Solution

1
2csharp
3public class Solution {
4    public string ToHex(int num) {
5        if (num == 0) return "0";
6        string hex = "0123456789abcdef", result = "";
7        while(num != 0 && result.Length < 8) {
8            result = hex[num & 15] + result;
9            num = num >> 4;
10        }
11        return result;        
12    }
13}

As like the above solutions, This C# solution follows the same approach to reach the desired solution.By demonstrating the process of converting a 32-bit signed integer to hexadecimal across various programming languages, it becomes apparent that the underlying logic is universal, although the syntax varies. The solutions demonstrated clearly articulate the approach one should take when engaging with this particular problem. A clear understanding of bitwise operations combined with control flow constructs is the main requisite in order to be able to successfully implement these solutions.

To summarize, the problem is tackled by trapping the last four bits of the number, translating it to the equivalent hexadecimal character and shifting the original number to the right for four bits. This loop continues until all bits of the number are processed.

As shown above, this approach can be implemented in various programming languages such as Python, Java, Javascript, C++ and C#, showing flexibility across a broad range of contexts.

It's important to mention that these solutions are built from scratch and do not rely on preexisting hexadecimal conversion functions that some programming languages provide, emphasizing the need of understanding fundamental algorithms and computer operations, rather than relying solely on higher level functions.

Applying these concepts to real world contexts, understanding the hexadecimal system is paramount within the fields of web development, cryptography, and memory address identification amongst others. By mastering these techniques, programmers can ensure an efficient manipulation and transformation of numerical data structures across various applications.


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫