Skip to content

Latest commit

 

History

History
34 lines (31 loc) · 632 Bytes

12.md

File metadata and controls

34 lines (31 loc) · 632 Bytes

题目地址

https://leetcode-cn.com/problems/integer-to-roman/

解答

def intToRoman(num):
    """ 整数转罗马数字 """
    if num < 1 or num > 3999:
        return None
    hashmap = {
        "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,
    }

    roman = ""
    while num:
        for k, v in hashmap.items():
            if num >= v:
                roman += k * (num // v)
                num -= v * (num // v)

    return roman