首页 > 代码库 > 13. Roman to Integer Leetcode Python

13. Roman to Integer Leetcode Python

Given a roman numeral, convert it to an integer.


Input is guaranteed to be within the range from 1 to 3999.

这题的做法和前面一体interger to roman 类似 建一个dictionary 去查询。 

1.先把string 反转

2. 用一个last去保存上一次的digit 

3.如果上次的digit 大于现在的digit 就将值减去两倍的digit 否则 相加。 

例如iv 反转过来是VI  直接加之后等于6 实际值为4 需要减去两倍的1 


代码如下

class Solution:
    # @return an integer
    def romanToInt(self, s):
        dict={'M':1000,'D':500,'C':100,'L':50,'X':10,'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
                
        
引用 http://www.cnblogs.com/zuoyuan/p/3779688.html

13. Roman to Integer Leetcode Python