class Solution:
def toHexspeak(self, num: str) -> str:
"""
1. convert num -> hex
2. map hex digit with O~A
3. get rem of each mod 16, cache rem into arr
4. convert
tc O(lgN) N: value of num sc O(lgN)
"""
d = {1:'I',0:'O',10:"A",11: "B",12: "C", 13:"D", 14:"E", 15:"F"}
x = []
y = int(num)
rem = y%16
if rem not in d:
return "ERROR"
while y>0:
x.append(y%16)
y = (y-y%16)/16
x = x[::-1]
for i,a in enumerate(x):
if a not in d:
return "ERROR" # early termination
x[i] = d[a]
return ''.join(x)
simple version
# tc, sc O(num.length())
class Solution:
def toHexspeak(self, num: str) -> str:
s = hex(int(num)).upper()[2 :].translate(str.maketrans('01', 'OI'))
return 'ERROR' if any(c.isdigit() for c in s) else s