LeetCode力扣018:罗马数字转整数

罗马数字转整数

LeetCode力扣018:罗马数字转整数_第1张图片

代码实现

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        n=len(s)
        sum=0
        for i in range(0,n):
            dic = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
            if i+1!=n:
                if s[i]=='I':
                    if s[i+1] == 'V' or s[i+1]=='X':
                        dic[s[i]]=-1
                if s[i]=='X':
                    if s[i+1] == 'L' or s[i+1]=='C':
                        dic[s[i]]=-10
                if s[i]=='C':
                    if s[i+1] == 'D' or s[i+1]=='M':
                        dic[s[i]]=-100
            sum+=dic[s[i]]
        return sum
 

你可能感兴趣的:(leetcode,linux,算法)