卖萌的弱渣

I am stupid, I am hungry.

Integer to Roman

Given an integer, convert it to a roman numeral.

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

Solution

  • Use two well designed table to record nums and associated romans
(Integer-to-Roman.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        # this two tables are really important
        nums = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
        romans = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
        result = ""
        for i in range(len(nums)):
            # it is not "if", because nums[i] could appear twice
            while num >= nums[i]:
                result += romans[i]
                num -= nums[i]

        return result