Skip to content

Commit adb157f

Browse files
authored
Create Convert a Number to Hexadecimal.py
1 parent 0792944 commit adb157f

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Convert a Number to Hexadecimal.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
'''
2+
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two’s complement method is used.
3+
4+
Note:
5+
6+
All letters in hexadecimal (a-f) must be in lowercase.
7+
The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
8+
The given number is guaranteed to fit within the range of a 32-bit signed integer.
9+
You must not use any method provided by the library which converts/formats the number to hex directly.
10+
Example 1:
11+
12+
Input:
13+
26
14+
15+
Output:
16+
"1a"
17+
Example 2:
18+
19+
Input:
20+
-1
21+
22+
Output:
23+
"ffffffff"
24+
'''
25+
26+
class Solution(object):
27+
def toHex(self, num):
28+
"""
29+
:type num: int
30+
:rtype: str
31+
"""
32+
33+
if num == 0:
34+
return '0'
35+
36+
res = ''
37+
while num != 0 and len(res) < 8:
38+
digit = num % 16
39+
if digit < 10:
40+
res = str(digit) + res
41+
else:
42+
res = chr(ord('a') + digit - 10) + res
43+
44+
num //= 16
45+
46+
return res

0 commit comments

Comments
 (0)