-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRoman_to_int.py
58 lines (49 loc) · 1.36 KB
/
Roman_to_int.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
47
48
49
50
51
52
53
54
55
56
57
58
class Solution:
def romanToInt(self, s: str) -> int:
"""
Converts a Roman numeral string to an integer.
Args:
s: A string representing a Roman numeral.
Returns:
An integer representing the converted value of the Roman numeral.
Examples:
>>> romanToInt("III")
3
>>> romanToInt("IX")
9
>>> romanToInt("LVIII")
58
"""
romans = {
'I':1,
'V':5,
'X':10,
'L': 50,
'C':100,
'D':500,
'M':1000
}
sum = 0
cache = 0
for char in s[::-1]:
current_value = romans[char]
if current_value < cache:
sum -= current_value
else:
sum += romans[char]
cache = romans[char]
return sum
"""class Solution:
def romanToInt(self, s: str) -> int:
decimal = 0
prev_value = 0
dict1 ={"I": 1,"V":5,"X":10,"L":50,"C":100, "D":500, "M" :1000}
lenght= len(s)
for x in reversed(s) :
value = dict1.get(x, 0)
if value < prev_value:
decimal -= value
else:
decimal += value
prev_value = value
return decimal"""