Leetcode: Roman to integer

来源:互联网 发布:怎样安装t3软件 编辑:程序博客网 时间:2024/06/05 19:07

题目:将罗马数字转换成整数,输入范围:[1,3999]

解题思路:罗马数字与阿拉伯数字对应关系:

1~9: {“I”, “II”, “III”, “IV”, “V”, “VI”, “VII”, “VIII”, “IX”};

10~90: {“X”, “XX”, “XXX”, “XL”, “L”, “LX”, “LXX”, “LXXX”, “XC”};

100~900: {“C”, “CC”, “CCC”, “CD”, “D”, “DC”, “DCC”, “DCCC”, “CM”};

1000~3000: {“M”, “MM”, “MMM”}.
即:I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)
当数字组合时,左边的数字小于右边的数字,减去左边的数字;左边的数字大于右边的数字,加上左边的数字,例如XCIX=99:
X

代码:

class Solution(object):    def romanToInt(self,s):        Roman={'M':1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}        ans=0        for i in range(0,len(s)-1):            curr=Roman[s[i]]            next=Roman[s[i+1]]            if curr>next:                ans +=curr            else:                ans -=curr        ans +=Roman[s[-1]]        return ans
0 0
原创粉丝点击