LeetCode 12 Integer to Roman

# -*- coding: utf-8 -*-
# @File  : leet_12.py
# @Author: FanyFull
# @Date  : 2021/9/20

class Solution:
    def intToRoman(self, num: int) -> str:
        number = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
        s = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
        res = ""

        for i in range(0, len(number)):
            while (num >= number[i]):
                res += s[i]
                num -= number[i]

            if num <= 0:
                break

        return res

if __name__ == '__main__':
    solution = Solution()
    input = 1994
    output = solution.intToRoman(input)
    print(output)

解这道题的巧妙之处就在于 numbers 这两个列表的使用,然后从数字的高位到低位挨个套用罗马字符即可。


LeetCode 12 Integer to Roman
http://fanyfull.github.io/2021/09/20/LeetCode-12-Integer-to-Roman/
作者
Fany Full
发布于
2021年9月20日
许可协议