12. Integer to Roman[M]整数转罗马数字

题目

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.


思路

思考罗马数字与整数的变换关系:
Symol|Value
:-:|:-:
I|1
V|5
X|10
L|50
C|100
D|500
M|1000
罗马数字通常按照从大到小从左到右的顺序排,字母累加以表示数字。但是注意,整数4的罗马数字不是IIII,而是IV。像这样的数字还有9、40等。于是重新考虑建立罗马数字与整数的变换表:
Symol|Value
:-:|:-:
I|1
IV|4
V|5
IX|9
X|10
XL|40
L|50
XC|90
C|100
CD|400
D|500
CM|900
M|1000
列举出所有情况下的符号,在表中查找数字num:

  1. 去Value表中找出不大于num的数字x
  2. 根据对应的Symbol输出字符,并将num-x
  3. 循环执行2操作,直到num为0

C++

 string intToRoman(int num) {
        string resStr = "";
        vector<int> value{1000,900,500,400,100,90,50,40,10,9,5,4,1};
        vector<string> symbol{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
        for(int i=0;i<value.size();i++)
            while(num>=value[i])
            {
                resStr+=symbol[i];
                num-=value[i];
            }
        return resStr;
    }

Python

 def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        intList = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
        strList = ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I']
        resStr = ''
        i = 0
        count = 0
        while num > 0:
            count = num/intList[i]
            num %= intList[i]
            while count > 0:
                resStr += strList[i]
                count -= 1
            i += 1
        return resStr

猜你喜欢

转载自www.cnblogs.com/Jessey-Ge/p/10993462.html