Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
首先大概了解一下罗马数字的规则,I, II, III, IV, V,等。参考这篇答案,写一下:
http://www.cnblogs.com/zuoyuan/p/3779688.html
首先反转一下字符,依次累加,但是当后一个小于前一个的时候,先减去两次,再相加。建立了名为last的flag,方便比较当前的和之前的大小。
当然还得建一个字典,方便”查表”,
numerals = { “M”: 1000, “D”: 500, “C”: 100, “L”: 50, “X”: 10, “V”: 5, “I”: 1 }
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
dic = { "M": 1000, "D": 500, "C": 100, "L": 50, "X": 10, "V": 5, "I": 1 }
s = s[::-1]
last = None
ans = 0
for i in s:
if last and dic[i] < last:
ans -= 2*dic[i]
ans += dic[i]
last = dic[i]
return ans