Leetcode 12. Integer to Roman

作者: Zentopia | 来源:发表于2018-03-12 17:50 被阅读13次

    Python 3 实现:

    源代码已上传 Github,持续更新。

    """
    12. Integer to Roman
    
    Given an integer, convert it to a roman numeral.
    
    Input is guaranteed to be within the range from 1 to 3999.
    """
    
    class Solution:
        def intToRoman(self, num):
            """
            :type num: int
            :rtype: str
            """
    
            integers = [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"]
            i = 0
            result = ""
    
            while i < len(integers):
                if num >= integers[i]:
                    result = result + romans[i]
                    num = num - integers[i]
                    i -= 1
    
                i += 1
    
            return result
    
    
    if __name__ == '__main__':
    
        solution = Solution()
        print(solution.intToRoman(2))
    

    相关文章

      网友评论

        本文标题:Leetcode 12. Integer to Roman

        本文链接:https://www.haomeiwen.com/subject/bgcofftx.html