[LeetCode][Python]12. Integer to

作者: bluescorpio | 来源:发表于2017-05-13 16:42 被阅读104次

    Given an integer, convert it to a roman numeral.

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

    罗马数字的表示:
    I - 1
    V - 5
    X - 10
    L - 50
    C - 100
    D - 500
    M - 1000
    

    罗马数字采用七个罗马字母作数字、即Ⅰ(1)、X(10)、C(100)、M(1000)、V(5)、L(50)、D(500)。记数的方法:

    1. 相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3;
    2. 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12;
    3. 小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9;

    思路:

    1. 题目要求最大输入值是3999,首先要得到罗马字母千位,百位,十位,个位的各个表达,然后用/和%号得到各位数的值,比如几个千位,几个百位,几个十位和几个个位。
    #!/usr/bin/env python
    # -*- coding: UTF-8 -*-
    class Solution(object):
        def intToRoman(self, num):
            """
            :type num: int
            :rtype: str
            """
            roman = [["", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"],
                     ["", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"],
                     ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"], ["", "M", "MM", "MMM"]]
            res = []
            res.append(roman[3][num / 1000 % 10])
            res.append(roman[2][num / 100 % 10])
            res.append(roman[1][num / 10 % 10])
            res.append(roman[0][num % 10])
            return "".join(res)
    
    
    if __name__ == '__main__':
        sol = Solution()
        num = 3999
        print sol.intToRoman(num)
        print sol.intToRoman(1980)
    

    相关文章

      网友评论

        本文标题:[LeetCode][Python]12. Integer to

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