leetcode 13. Roman to Integer

给一个罗马数字,转化成整数。这个就简单点了,直接从前往后扫,只需要注意一个规则,如果小单位在大单位前,小单位位负,小单位在大单位后,小单位为正。

class Solution(object):
    def cov(self,s):
        if s == 'I': return 1
        elif s == 'V': return 5
        elif s == 'X': return 10
        elif s == 'L': return 50
        elif s == 'C': return 100
        elif s == 'D': return 500
        elif s == 'M': return 1000

    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        lenS = len(s)
        a = [0 for i in range(lenS + 2)]
        for i in range(lenS):
            a[i] = self.cov(s[i])
        
        res = 0
        for i in range(lenS):
            if a[i] < a[i+1]:res -= a[i]
            else : res += a[i]
        return res  


你可能感兴趣的:(杂题)