leetcode13 罗马数字转整数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012343179/article/details/89785755

思路:这题懂了就非常简单。首先建立一个HashMap来映射符号和值,然后对字符串从左到右来,如果当前字符代表的值不小于其右边,就加上该值;否则就减去该值。以此类推到最左边的数,最终得到的结果即是答案。

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        d={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
        i=0
        result=0
        while i<len(s)-1:
            if d[s[i]]<d[s[i+1]]:
                result-=d[s[i]]
            else:
                result+=d[s[i]]
            i+=1
        result+=d[s[i]]
        return result

猜你喜欢

转载自blog.csdn.net/u012343179/article/details/89785755