算法33--Integer to Roman

Roman numerals are represented by seven different symbols: IVXLCD 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.

由于输入限制在1--3999

考虑个十百千位的取值以及对应的字符,找规律:

数字 g个 s十 b百 q千
1--3 I--III X---XXX C---CCC M--MMM
4 IX XL CD  
5 V L D  
6--8 VI--VIII LX---LXXX DC---DCCC  
9 IX XC CM  
0 k空      
class Solution:
    def intToRoman(self, num):
        s10 = ['I','X','C','M']
        s5 = ['V','L','D']
        tmp = 1000
        t = 0
        r = ''
        index = 3
        while num>0:
            t = int(num/tmp)
            #print(t, tmp, index)
            if t>=1 and t<=3:
                r = r + s10[index]*t
            elif t==4:
                r = r + s10[index] + s5[index]
            elif t==5:
                r = r + s5[index]
            elif t>=6 and t<=8:
                r = r + s5[index] + s10[index]*(t-5)
            elif t==9:
                r = r + s10[index] +s10[index+1]
            num = num % tmp
            tmp = tmp/10 
            index -= 1
        return r

s10保存十进制的1,10,100,1000取值

s5保存5位置的5,50,500情况

r保存最终结果

每一位的数字构成由s10以及s5来进行组合输出,分情况输出即可,没啥意思。

看了一下别人解法,感觉还是遍历所有情况:

public static String intToRoman(int num) {
    String M[] = {"", "M", "MM", "MMM"};
    String C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
    String X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
    String I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
    return M[num/1000] + C[(num%1000)/100] + X[(num%100)/10] + I[num%10];
}

 

 

猜你喜欢

转载自blog.csdn.net/u014106644/article/details/84231840