-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13_RomanToInt.py
46 lines (41 loc) · 1.01 KB
/
13_RomanToInt.py
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
41
42
43
44
45
46
def romanToInt(s: str) -> int:
roman_int = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
}
if len(s) == 1:
return roman_int[s]
s = s.replace("IV","IIII").replace("IX","VIIII")
s = s.replace("XL", "XXXX").replace("XC", "LXXXX")
s = s.replace("CD", "CCCC").replace("CM", "DCCCC")
result = 0
for each in s:
result += roman_int[each]
return result
## solution 2
class Solution:
def romanToInt(self, s: str) -> int:
roman_int = {
"I": 1,
"V": 5,
"X": 10,
"L": 50,
"C": 100,
"D": 500,
"M": 1000,
}
result = 0
prev = 0
for char in s[::-1]:
curr = roman_int[char]
if curr < prev:
result -= curr
else:
result += curr
prev = curr
return result