Question:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
The meaning of the question is very simple. It refers to converting a string of Roman numerals into an integer.
First, we need to have a basic understanding of the Roman numerals, because the number size has been limited to 1 ~ 3999, so we only need to consider the number of thousands, without complicated problems such as numerical segmentation.
The unit of the Roman numerals is briefly listed below: 'I '1; 'V' 5; 'X' 10; 'l' 50; 'C' 100; 'D' 500; 'M' 1000
The size of a number is the sum of the numbers represented by the characters in it. The combination rule of the numbers is: I x C will add or subtract the values due to different positions. For example, the IV value is 4, the VI value is 6, the CD value is 400, and the DC value is 600. V l d m in 1 ~ This problem does not exist in the range of 3999.
Finally, we chose a method that only needs to traverse the string once, that is, to traverse the Roman numeric string from the end. If I (x, c) appears, if the value of the traversed part is higher than V (L, d), then the I (x, c) value is subtracted from the existing result. Otherwise, the value is added.
To sum up, the key to this question is to find the rule and finally use the code ~
class Solution: # @return an integer def romanToInt(self, s): L=len(s) res=0 for i in range(L-1,-1,-1): a=s[i] if a=='I': if res>=5: res-=1 else: res+=1 elif a=='V': res+=5 elif a=='X': if res>=50: res-=10 else: res+=10 elif a=='L': res+=50 elif a=='C': if res>=500: res-=100 else: res+=100 elif a=='D': res+=500 elif a=='M': res+=1000 return res
Leetcode_num14_roman to integer