12. Integer to Roman python leetcode 2016 new Season

来源:互联网 发布:赛尔网络 ipv6项目 编辑:程序博客网 时间:2024/06/03 20:51

Given an integer, convert it to a roman numeral.

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


store the roman and values in arrays and iterate array to get the value. takes O(1) space and O(n) time

class Solution(object):    def intToRoman(self, num):        """        :type num: int        :rtype: str        """        values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]        roman = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']        result = ''        for index in range(len(values)):            while num >= values[index]:                result += roman[index]                num -=  values[index]        return result


0 0
原创粉丝点击