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.

SymolValue
I1
V5
X10
L50
C100
D500
M1000

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.

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

思路


思考罗马数字与整数的变换关系:罗马数字通常按照从大到小从左到右的顺序排,字母累加以表示数字。但是注意,整数4的罗马数字不是IIII,而是IV。像这样的数字还有9、40等。于是重新考虑建立罗马数字与整数的变换表:

SymolValue
I1
IV4
V5
IX9
X10
XL40
L50
XC90
C100
CD400
D500
CM900
M1000

列举出所有情况下的符号,在表中查找数字num:

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

C++

class Solution {
public:
    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

转载于:https://www.cnblogs.com/Jessey-Ge/p/10993462.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值