Leetcode: Roman to Integer

来源:互联网 发布:微商城与淘宝的区别 编辑:程序博客网 时间:2024/06/04 00:04

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

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
0 0
原创粉丝点击