I'm trying to write some code that converts roman numerals into integers, but I'm running into an issue where when I input 'MCMXCIV', I'm getting 3099 instead of 1994. When I try with smaller numbers like III (3) and LVIII (58), it's converting them correctly. I know there's a more efficient way to write this whole thing, but any assistance with debugging my current code would be much appreciated.
Rules: I can be placed before V (5) and X (10) to make 4 and 9. X can be placed before L (50) and C (100) to make 40 and 90. C can be placed before D (500) and M (1000) to make 400 and 900.
class Solution:
def romanToInt(self, s: str) -> int:
romanDict = {
'I':1,
'V':5,
'X':10,
'L':50,
'C':100,
'D':500,
'M':1000
}
l = len(s)
sum = 0
i = 0
for i in range(l):
letter = s[i]
if i+1 < l:
nextLetter = s[i+1]
diff = romanDict[nextLetter] - romanDict[letter]
match letter:
case 'I':
if nextLetter in ['V', 'X']:
sum += romanDict[nextLetter] - romanDict[letter]
print (diff)
i + 1
else: sum += romanDict[letter]
case 'X':
if nextLetter in ['L', 'C']:
sum += romanDict[nextLetter] - romanDict[letter]
print (diff)
i + 1
else: sum += romanDict[letter]
case 'C':
if nextLetter in ['D', 'M']:
sum += romanDict[nextLetter] - romanDict[letter]
print (diff)
i + 1
else: sum += romanDict[letter]
case _:
sum += romanDict[letter]
print (romanDict[letter])
else: sum += romanDict[letter]
return sum