LeetCode T12 T13

在这里插入图片描述
在这里插入图片描述

class Solution:
    def intToRoman(self, num):
        chD = ['I', 'V', 'X', 'L', 'C', 'D', 'M']
        def getCh(index, valStr):

            digit = int(valStr)
            if digit==0:
                return ''
            if digit < 5:
                if digit == 4:
                    return chD[index] + chD[index+1]
                else:
                    return chD[index]*digit
            elif int(valStr) > 5:
                if digit==9:
                    return chD[index] + chD[index+2]
                else:
                    digit = digit%5
                    return chD[index+1] + chD[index]*digit
            else:
                return chD[index+1]
        D = str(num)
        n = len(D)
        s = ""
        for i,d in enumerate(D):
            s += getCh(2*n-2*i-2,d)
        return s

在这里插入图片描述

在这里插入图片描述在这里插入图片描述

class Solution:
    def romanToInt(self, s):
        d = dict()
        d['M'] = 1000
        d['D'] = 500
        d['C'] = 100
        d['L'] = 50
        d['X'] = 10
        d['V'] = 5
        d['I'] = 1
        count = 0
        n = len(s)
        sum_D = 0
        flag = True
        while(count < n-1):
            tempP = d[s[count]]
            tempF = d[s[count + 1]]
            if tempP < tempF:
                sum_D += tempF - tempP
                if count + 1 == n-1:
                    flag = False
                    break
                count += 2
            else:
                sum_D += tempP
                count += 1
        if flag:
            sum_D += d[s[count]]
        
        return sum_D

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wjl__ai__/article/details/112055944