Skip to content

Commit b4effef

Browse files
committed
hexadecimal
1 parent 302931e commit b4effef

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""
2+
Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two's complement method is
3+
used.
4+
5+
Note:
6+
7+
All letters in hexadecimal (a-f) must be in lowercase.
8+
The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero
9+
character '0'; otherwise, the first character in the hexadecimal string will not be the zero character.
10+
The given number is guaranteed to fit within the range of a 32-bit signed integer.
11+
You must not use any method provided by the library which converts/formats the number to hex directly.
12+
Example 1:
13+
14+
Input:
15+
26
16+
17+
Output:
18+
"1a"
19+
Example 2:
20+
21+
Input:
22+
-1
23+
24+
Output:
25+
"ffffffff"
26+
"""
27+
__author__ = 'Daniel'
28+
29+
30+
class Solution(object):
31+
def toHex(self, num):
32+
"""
33+
All use bit manipulation
34+
:type num: int
35+
:rtype: str
36+
"""
37+
ret = []
38+
while len(ret) < 8 and num:
39+
ret.append(self.encode(num & 0xf))
40+
num >>= 4
41+
42+
return ''.join(ret[::-1]) or '0'
43+
44+
def toHexNormal(self, num):
45+
"""
46+
Python arithmetic handles the negative number very well
47+
:type num: int
48+
:rtype: str
49+
"""
50+
ret = []
51+
while len(ret) < 8 and num:
52+
ret.append(self.encode(num % 16))
53+
num /= 16
54+
55+
return ''.join(ret[::-1]) or '0'
56+
57+
def encode(self, d):
58+
if 0 <= d < 10:
59+
return str(d)
60+
61+
return chr(ord('a') + d - 10)
62+
63+
64+
if __name__ == "__main__":
65+
assert Solution().toHex(-1) == 'ffffffff'

0 commit comments

Comments
 (0)