Leetcode-Python 整数转罗马数字

Leetcode-Python 整数转罗马数字_第1张图片

Leetcode-Python 整数转罗马数字_第2张图片

class Solution:
    def intToRoman(self, num: int) -> str:
        string = str(num)
        result = ''
        length = len(string)
        for s in range(length):
            e_num = int(string[s])*(10**(length-s-1))
            if e_num < 4000 and e_num >= 1000:
                result += (int(e_num/1000)*'M')
            if e_num == 900:
                result += 'CM'
            if e_num < 900 and e_num >= 500:
                result += ('D'+(int(e_num/100)-5)*'C')
            if e_num == 400:
                result += 'CD'
            if e_num < 400 and e_num >= 100:
                result += (int(e_num/100)*'C')
            if e_num == 90:
                result += 'XC'
            if e_num < 90 and e_num >= 50:
                result += ('L'+(int(e_num/10)-5)*'X')
            if e_num == 40:
                result += 'XL'
            if e_num < 40 and e_num >= 10:
                result += (int(e_num/10)*'X')
            if e_num == 9:
                result += 'IX'
            if e_num < 9 and e_num >= 5:
                result += ('V'+((e_num-5)*'I'))
            if e_num == 4:
                result += 'IV'
            if e_num < 4 and e_num >= 1:
                result += e_num*'I'
        return result

github项目地址:https://github.com/JockWang/LeetCode-Python

你可能感兴趣的:(Leetcode)