LeetCode Notes_#12 Integer to Roman

LeetCode Notes_#12 Integer to Roman

Contents

Problem

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

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.

Example 1:

Input: 3
Output: "III"

Example 2:

Input: 4
Output: "IV"

Example 3:

Input: 9
Output: "IX"

Example 4:

Input: 58
Output: "LVIII"
Explanation: C = 100, L = 50, XXX = 30 and III = 3.

Example 5:

Input: 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV= 4

Solution

思路

这一题是13.Roman to Integer的对称题
要将数字按位拆分开,拿1994为例

Input: 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4

依次取出千位,百位,十位,个位,然后依次转化为罗马数字,再拼接起来即可
要考虑到整千,整百的状况,这时候就不可以一位一位取了(首先遍历一遍看看有几个0?从非0的才开始转换)
问题:对于每一位来说,都有几种情况

3->III(叠加) 8->VIII(后缀) 4->IV(前缀)
300->CCC 800->DCCC 400->CD
...

如何去区分这些形式呢?4,9,5,1这种可以使用字典,其他的使用条件语句,具体见代码

代码

class Solution(object):
    def intToRoman(self, num):
        """
        :type num: int
        :rtype: str
        """
        d={1:'I',4:'IV',5:'V',9:'IX',10:'X',40:'XL',50:'L',90:'XC',100:'C',400:'CD',500:'D',900:'CM',1000:'M'}
        i=1
        tmp=num
        roman=""
        while(tmp>0):
            a=tmp%10#a是某一位数字
            if a<4:
                roman=a*d[i]+roman#从个位开始,新的字母加到左边
            elif a>5 and a<9:
                roman=d[5*i]+(a-5)*d[i]+roman
            else:
                roman=d[a*i]+roman
            i=i*10#这个用来表示1,10,100,1000这些单位
            tmp=tmp/10
        return roman

96ms,faster than 35%

原文地址:https://www.cnblogs.com/Howfars/p/9749973.html