Given a Roman numeral, convert it to an integer.
Input is guaranteed to being within the range from 1 to 3999.
The practice of this problem and the previous one interger to Roman similar to build a dictionary to query.
1. Reverse the string first
2. Use one last to save the previous digit
3. If the last digit is greater than the current digit, subtract the value by twice times digit otherwise add.
For example, iv inversion is the VI direct plus after equals 6 actual value of 4 need to subtract twice times 1
The code is as follows
Class solution: # @return An integer def romantoint (self, s): dict={' M ': +, ' D ': $, ' C ': +, ' L ': ' X ' : Ten, ' V ': 5, ' I ': 1} last=none sum=0 s=s[::-1] for Elem in S: if Last and Dict[last]>dict[elem]: Sum-=2*dict[elem] Sum+=dict[elem] last=elem return sum
Reference http://www.cnblogs.com/zuoyuan/p/3779688.html
Roman to Integer Leetcode Python