美文网首页
12-13. Roman and Integer [Medium

12-13. Roman and Integer [Medium

作者: 一个想当大佬的菜鸡 | 来源:发表于2019-05-04 18:44 被阅读0次

12. Integer to Roman


12. Integer to Roman
class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        res = ''
        roman = ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']
        number = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
        for i in range(len(roman)):
            while num >= number[i]:
                res = res + roman[i]
                num -= number[i]
        return res

13. Roman to Integer

13. Roman to Integer
class Solution(object):
    def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        dic = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
        res = 0
        for i in range(len(s)):
            if i < len(s) - 1 and dic[s[i]] < dic[s[i+1]]:
                res -= dic[s[i]]
            else:
                res += dic[s[i]]
        return res

相关文章

网友评论

      本文标题:12-13. Roman and Integer [Medium

      本文链接:https://www.haomeiwen.com/subject/dxdfoqtx.html