1
+ """
2
+ Roman numerals are represented by seven different symbols:
3
+ I, V, X, L, C, D and M.
4
+
5
+ Symbol Value
6
+ I 1
7
+ V 5
8
+ X 10
9
+ L 50
10
+ C 100
11
+ D 500
12
+ M 1000
13
+ For example, 2 is written as II in Roman numeral, just two
14
+ one's added together. 12 is written as XII, which is simply X + II.
15
+ The number 27 is written as XXVII, which is XX + V + II.
16
+
17
+ Roman numerals are usually written largest to smallest from left to
18
+ right. However, the numeral for four is not IIII. Instead, the number
19
+ four is written as IV. Because the one is before the five we subtract
20
+ it making four. The same principle applies to the number nine, which
21
+ is written as IX. There are six instances where subtraction is used:
22
+
23
+ - I can be placed before V (5) and X (10) to make 4 and 9.
24
+ - X can be placed before L (50) and C (100) to make 40 and 90.
25
+ - C can be placed before D (500) and M (1000) to make 400 and 900.
26
+
27
+ Given a roman numeral, convert it to an integer.
28
+
29
+ Example 1:
30
+ Input: s = "III"
31
+ Output: 3
32
+ Explanation: III = 3.
33
+
34
+ Example 2:
35
+ Input: s = "LVIII"
36
+ Output: 58
37
+ Explanation: L = 50, V= 5, III = 3.
38
+
39
+ Example 3:
40
+ Input: s = "MCMXCIV"
41
+ Output: 1994
42
+ Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
43
+
44
+ Constraints:
45
+ * 1 <= s.length <= 15
46
+ * s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M').
47
+ * It is guaranteed that s is a valid roman numeral in the range [1, 3999].
48
+ """
49
+
50
+ class Solution :
51
+ # O(n) approach, using two mappings
52
+ #def romanToInt(self, s: str) -> int:
53
+ # mapping = {'I':1, 'V':5, 'X':10, 'L':50,
54
+ # 'C':100, 'D':500, 'M':1000}
55
+
56
+ # special = {'IV':4, 'IX':9, 'XL': 40, 'XC':90,
57
+ # 'CD':400, 'CM':900}
58
+
59
+ # t = 0
60
+ # i = 0
61
+ # while i < len(s):
62
+ # if i < len(s) - 1 and s[i:i+2] in special:
63
+ # t += special[s[i:i+2]]
64
+ # i += 2
65
+ # else:
66
+ # t += mapping[s[i]]
67
+ # i += 1
68
+
69
+ # return t
70
+
71
+ # O(n) approach, but we go from right to left -
72
+ # if s[i] < s[i+1], then we subtract s[i] instead of
73
+ # adding it
74
+ def romanToInt (self , s : str ) -> int :
75
+ mapping = {'I' :1 , 'V' :5 , 'X' :10 , 'L' :50 ,
76
+ 'C' :100 , 'D' :500 , 'M' :1000 }
77
+
78
+ t = mapping [s [len (s )- 1 ]]
79
+ i = len (s ) - 2
80
+ while i >= 0 :
81
+ factor = 1
82
+ if mapping [s [i ]] < mapping [s [i + 1 ]]:
83
+ factor = - 1
84
+
85
+ t += factor * mapping [s [i ]]
86
+ i -= 1
87
+
88
+ return t
0 commit comments