Last active
January 8, 2020 16:28
-
-
Save alastairparagas/885ce7856ca9728283b762886849fa39 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution(object): | |
def intToRoman(self, num): | |
""" | |
:type num: int | |
:rtype: str | |
""" | |
conversion_map = { | |
1: "I", | |
5: "V", | |
10: "X", | |
50: "L", | |
100: "C", | |
500: "D", | |
1000: "M" | |
} | |
subtraction_instances = { | |
4: "IV", | |
9: "IX", | |
40: "XL", | |
90: "XC", | |
400: "CD", | |
900: "CM" | |
} | |
numerics = sorted(conversion_map.keys(), reverse=True) | |
leftover = num | |
place = 10 | |
built_str = "" | |
while leftover > 0: | |
processed = leftover % place | |
subtraction_instance = subtraction_instances.get(processed) | |
if subtraction_instance: | |
built_str = subtraction_instance + built_str | |
else: | |
for i, numeric in enumerate(numerics): | |
if processed >= numeric: | |
if numeric == 1: | |
built_str = "".join( | |
"I" | |
for _ in range(processed) | |
) + built_str | |
else: | |
built_str = "{0}{1}".format( | |
conversion_map.get(numeric), | |
"".join( | |
conversion_map.get(numerics[i+1]) | |
for _ in range(processed-numerics) | |
) | |
) + built_str | |
break | |
leftover -= processed | |
place *= 10 | |
return built_str | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment