forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hexspeak.py
32 lines (29 loc) · 793 Bytes
/
hexspeak.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Time: O(n)
# Space: O(1)
class Solution(object):
def toHexspeak(self, num):
"""
:type num: str
:rtype: str
"""
lookup = {0:'O', 1:'I'}
for i in xrange(6):
lookup[10+i] = chr(ord('A')+i)
result = []
n = int(num)
while n:
n, r = divmod(n, 16)
if r not in lookup:
return "ERROR"
result.append(lookup[r])
return "".join(reversed(result))
# Time: O(n)
# Space: O(n)
class Solution2(object):
def toHexspeak(self, num):
"""
:type num: str
:rtype: str
"""
result = hex(int(num)).upper()[2:].replace('0', 'O').replace('1', 'I')
return result if all(c in "ABCDEFOI" for c in result) else "ERROR"