您的位置:首页 > 其它

Leetcode: Roman to Integer

2015-08-26 23:25 260 查看

Question

Given a roman numeral, convert it to an integer.

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

Show Tags

Show Similar Problems

Solution

Code

[code]class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """

        if s=="":
            return 0
        res = 0
        for ind,elem in enumerate(s):
            if elem=='I':
                if ind<len(s)-1 and (s[ind+1]=='V' or s[ind+1]=="X"):
                    res -= 1
                else:
                    res += 1
            if elem=='V':
                res += 5
            if elem=='X':
                if ind<len(s)-1 and (s[ind+1]=='L' or s[ind+1]=="C"):
                    res -= 10
                else:
                    res += 10
            if elem=='L':
                res += 50
            if elem=='C':
                if ind<len(s)-1 and (s[ind+1]=='D' or s[ind+1]=="M"):
                    res -= 100
                else:
                    res += 100
            if elem=='D':
                res += 500
            if elem=='M':
                res += 1000

        return res
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: