requirements
Roman numerals contain the following seven characters: I, V, X, L, C, D and M.
Character values I 1 V 5 X 10 L 50 C 100 D 500 M 1000Copy the code
For example, the Roman numeral 2 is written as II, which is two ones side by side. Write XII as X + II. Write XXVII as XX + V + II.
Usually, the smaller Roman numerals are to the right of the larger numerals. But there are exceptions, for example, 4 is not written as IIII, it’s written as IV. The number 1 is to the left of the number 5 and represents the number 4 when the larger number 5 decreases by 1. Similarly, the number 9 represents IX. This particular rule applies only to the following six situations:
I can be put to the left of V (5) and X (10) to represent 4 and 9. X can be placed to the left of L (50) and C (100) to represent 40 and 90. C can be put to the left of D (500) and M (1000) to represent 400 and 900. Given a Roman numeral, convert it to an integer.
Example 1:
Input: s = "III" Output: 3Copy the code
Example 2:
Input: s = "IV" Output: 4Copy the code
Example 3:
Input: s = "IX" Output: 9Copy the code
Example 4:
Input: S = "LVIII" Output: 58 Interpretation: L = 50, V= 5, III = 3Copy the code
Example 5:
Input: S = "MCMXCIV" Output: 1994 Interpretation: M = 1000, CM = 900, XC = 90, IV = 4Copy the code
Tip:
- 1 <= s.length <= 15
- S contains only characters (‘I’, ‘V’, ‘X’, ‘L’, ‘C’, ‘D’, ‘M’)
- The data guarantees that s is a valid Roman numeral and represents an integer within the range [1, 3999]
- All test cases are in accordance with the Roman numerals writing rules, and there will be no cross-position.
- Examples like IL and IM don’t fit the question, 49 should be XLIX, 999 should be CMXCIX.
- For detailed rules for writing Roman numerals, see Roman numerals – Mathematics.
The core code
class Solution:
def romanToInt(self, s: str) - >int:
ans = 0
a = {'I':1.'V':5.'X':10.'L':50.'C':100.'D':500.'M':1000}
for i in range(len(s)):
if i < len(s) - 1 and a[s[i]] < a[s[i + 1]]:
ans -= a[s[i]]
else:
ans += a[s[i]]
return ans
Copy the code
We find that MCM is 1000 + 900 = 1000-100 + 1000, so we scan the data once. When we find that the following data is smaller than the preceding data, we can subtract the current value and add it directly.