leetcode 罗马数字与整数互转

leetcode 13.罗马数字转整数

class Solution(object):
    def romanToInt(self, s):
        res = 0
        roman = dict(I=1, V=5, X=10, L=50, C=100, D=500, M=1000)
        for i in range(len(s)-1):
            if roman.get(s[i])>=roman.get(s[i+1]):
                res += roman.get(s[i])
            else:
                res -= roman.get(s[i])
        res += roman.get(s[len(s)-1])
        return res
# 求解
s = Solution()
s.romanToInt('LVIII')
# return
58

leetcode 12.整数转罗马数字

class Solution(object):
    def intToRoman(self, num):
        rules = (
            ('M', 1000),
            ('CM', 900), ('D', 500), ('CD', 400), ('C', 100),
            ('XC', 90), ('L', 50), ('XL', 40), ('X', 10),
            ('IX', 9), ('V', 5), ('IV', 4), ('I', 1),
            )
        res = []
        for roman, dec in rules:
            res.extend([roman]*(num//dec))
            num = num%dec
        return ''.join(res)
# 求解
s = Solution()
s.intToRoman(1994)
# return
'MCMXCIV'

上一篇:整数转罗马数字(Integer to Roman)


下一篇:13.罗马数字转整数(Roman to Integer)