LeetCode #12 – Integer to Roman

LeetCode题目链接

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

题意:给定阿拉伯数字,转化为罗马数字

QQ截图20150610221408

打表记录可能出现的罗马数字,从高位开始处理。

class Solution:
    def intToRoman(self, num):
        a = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
        b = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I')
        res = ''
        for i in range(len(a)):
            while num >= a[i]:
                num -= a[i]
                res += b[i]
        return res

欢迎留言