Leetcode 13. Roman to Integer The Solution of Python

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Python:

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic={'M':1000,'D':500,'C':100,'L':50,'X':10,'V':5,'I':1}
        res,pre=0,0
        for index,n in enumerate(s[::-1]):
            if dic[n]>=pre:
                res+=dic[n]
            else:
                res-=dic[n]
            pre=dic[n]
        return res

和上一题一样,比较简单,这里还有别人的一种思路。
Python 2:

class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = {
            'I': lambda i: -1 if s[i + 1] in ['V', 'X'] else 1,
            'X': lambda i: -10 if s[i + 1] in ['L', 'C'] else 10,
            'C': lambda i: -100 if s[i + 1] in ['D', 'M'] else 100,
            'V': lambda i: 5,
            'L': lambda i: 50,
            'D': lambda i: 500,
            'M': lambda i: 1000,
        }
        x = 0
        s += '@'
        for i, ch in enumerate(s[:-1]):
            x += dic[ch](i)
        return x

附上罗马数字的换算方法:
(1)基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个;
(2)不能把基本数字 V 、L 、D中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个;
(3)V 和 X 左边的小数字只能用 Ⅰ;
(4)L 和 C 左边的小数字只能用 X;
(5)D 和 M 左边的小数字只能用 C。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值