Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
分析: 首先不超过3999,数字不大,不用考虑很复杂。 复习罗马数字的表示方式
"M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1
如果将原roman翻转,从小往大相加,就可以成立。 考虑特殊情况,CM=900,如果翻转后是MC=1100,不符合。 所以看见这个特殊情况,前面的M > 后面的C,将总和 - 200. 就ok了。说实话,这个特殊情况不是我事先能考虑的,中国人用罗马数字的需求太少,我就不知道CM是900. 还好就这一个特殊case特殊处理了。
class Solution:
# @return an integer
def romanToInt(self, s):
dict = { "M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1 }
sum = 0
s = s[::-1]
last = None
for x in s:
if last and dict[x] < last:
sum -= 2 * dict[x]
sum += dict[x]
last = dict[x]
return sum