405. Convert a Number to Hexadecimal

Dhanaraj S
1 min readFeb 17, 2022

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

Approach 1:

Find the 4 LSB bits in each iteration. And convert that into hexadecimal and finally return the value. For negative number we want to make sure that iterations don’t exceed 8 times.

class Solution:
def toHex(self, num: int) -> str:
value="0123456789abcdef"
result,cnt="",0
while(num>0 or (num<0 and cnt<8)):
result=value[(num&15)]+result
num>>=4
cnt+=1
return(result if result!="" else "0")

Time :O(c)

Space: O(1)

Approach 2:

The same approach 1 can be done in a different way, by assuming the negative number received as positive number. That is assuming the binary form of the negative number as positive number . Here we add 2**32 to the negative number for it to be considered as positive number. Then follow the same approach in 1st case to convert it to hex.

class Solution:
def toHex(self, num: int) -> str:
binhex="0123456789abcdef"
result=""
if(num<0):
num=2**32+num
while(num>0):
result=binhex[(num&15)]+result
num>>=4
return([result,"0"][result==""])

Time :O(c)

Space: O(1)

--

--

Dhanaraj S

Tech-Enthusiast, Coder,Explorer,Geeky,Software Engineer |A piece of code delivers everything that you need. The world is all about codes.