""" 0013.1 - Roman to Integer - Solution 1 - Hash Map with Subtraction Rule """
#####################################################################################
# Imports
#####################################################################################
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def romanToInt(self, s: str) -> int:
"""Roman to Integer Function"""
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
ans = 0
for a, b in zip(s, s[1:]):
if roman[a] < roman[b]:
ans -= roman[a]
else:
ans += roman[a]
return ans + roman[s[-1]]
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().romanToInt("III")) # 3
print(Solution().romanToInt("LVIII")) # 58
print(Solution().romanToInt("MCMXCIV")) # 1994
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()
""" 0013.2 - Roman to Integer - Solution 2 - Right-to-Left Traversal """
#####################################################################################
# Imports
#####################################################################################
#####################################################################################
# Classes
#####################################################################################
class Solution:
"""Solution Class"""
def romanToInt(self, s: str) -> int:
"""Roman to Integer Function"""
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
ans = 0
prev = 0
for ch in reversed(s):
curr = roman[ch]
if curr < prev:
ans -= curr
else:
ans += curr
prev = curr
return ans
#####################################################################################
# Functions
#####################################################################################
def testcase():
"""Test Function"""
print(Solution().romanToInt("III")) # 3
print(Solution().romanToInt("LVIII")) # 58
print(Solution().romanToInt("MCMXCIV")) # 1994
#####################################################################################
# Main
#####################################################################################
if __name__ == "__main__":
testcase()