1. 程式人生 > >演算法33--Integer to Roman

演算法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];
}