Algorithm
Problem Name: 405. Convert a Number to Hexadecimal
Given an 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
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
class Solution {
char[] map = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
public String toHex(int num) {
if(num == 0) return "0";
String result = "";
while(num != 0){
result = map[(num & 15)] + result;
num = (num >>> 4);
}
return result;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Javascript Programming
Code -
Javascript Programming
const toHex = function(num) {
const bin = (num >>> 0).toString(2)
const arr = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
const mod = bin.length % 4
const r = []
if(mod !== 0 ){
r.push(arr[ parseInt(bin.slice(0, mod),2) ])
}
for(let i = mod; i < bin.length; i = i + 4) {
r.push(arr[ parseInt(bin.slice(i, i+4),2) ])
}
return r.join('')
};
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Python Programming
Code -
Python Programming
class Solution:
def toHex(self, num):
if not num: return "0"
mp, ans = "0123456789abcdef", ""
for i in range(8):
n = num & 15
c = mp[n]
ans = c + ans
num = num >> 4
return ans.lstrip('0')
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with C# Programming
Code -
C# Programming
using System.Linq;
using System.Text;
namespace LeetCode
{
public class _0405_ConvertANumberToHexadecimal
{
public string ToHex(int num)
{
if (num == 0) return "0";
var map = "0123456789abcdef";
var sb = new StringBuilder();
while (num != 0 && sb.Length < 8)
{
sb.Append(map[num & 15]);
num >>= 4;
}
return new string(sb.ToString().ToCharArray().Reverse().ToArray());
}
}
}
Copy The Code &
Try With Live Editor
Input
Output