13. Roman to Integer

来源:互联网 发布:sarah brightman 知乎 编辑:程序博客网 时间:2024/06/05 17:00

Given a roman numeral, convert it to an integer.

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


class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        l=len(s)
        r=0
        i=0
        roman={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'CM':900,'CD':400,'XC':90,'XL':40,'IX':9,'IV':4}
        while i<l:
            if i < l-1 and roman.has_key(s[i:i+2]):
                r=r+roman[s[i:i+2]]
                i=i+2
            else:
                r=r+roman[s[i]]
                i+=1
        return r

0 0