-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy path13-roman-to-integer.py
More file actions
40 lines (33 loc) · 1.15 KB
/
13-roman-to-integer.py
File metadata and controls
40 lines (33 loc) · 1.15 KB
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
33
34
35
36
37
38
39
40
class Solution:
def romanToInt(self, s: str) -> int:
roman_values = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
total = 0
prev_value = 0
# Iterate from right to left
for i in range(len(s) - 1, -1, -1):
current_value = roman_values[s[i]]
if current_value < prev_value:
total -= current_value
else:
total += current_value
prev_value = current_value
return total
# Test cases
if __name__ == "__main__":
sol = Solution()
print("Testing Roman to Integer:")
print(f"\"III\" -> {sol.romanToInt("III")} (Expected: 3)")
print(f"\"LVIII\" -> {sol.romanToInt("LVIII")} (Expected: 58)")
print(f"\"MCMXCIV\" -> {sol.romanToInt("MCMXCIV")} (Expected: 1994)")
print(f"\"IX\" -> {sol.romanToInt("IX")} (Expected: 9)")
print(f"\"IV\" -> {sol.romanToInt("IV")} (Expected: 4)")
print(f"\"I\" -> {sol.romanToInt("I")} (Expected: 1)")
print(f"\"MMMCMXCIX\" -> {sol.romanToInt("MMMCMXCIX")} (Expected: 3999)")