Given an integer, convert it to a Roman numeral.
Input is guaranteed to being within the range from 1 to 3999.
Converts an integer to Roman numerals. Need to know some rules of Roman numerals, see Wikipedia. The main need to pay attention to is the existence of the left minus, while the left minus also limited to I, X, c three numbers. In order to avoid the computational complexity caused by left subtraction, the combination of left subtraction can be expressed directly. Direct expansion of the original digital situation.
I:1
Iv:4
V:5ix:9
X:10xl:40
L:50xc:90
c:100cd:400
d:500cm:900
m:1000
It is very simple to combine the numbers of these combinations with the computations in decimal, and then add the letters or combinations of letters to the string, and then continue to advance to the low values. At the same time, because of the combination of the number table, the value of adjacent to the maximum of four times times the relationship, effectively avoid the same number repeated more than three times, in line with the provisions of Roman numerals.
s = 3978
3978/1000 = 3:mmm978> (1000-100), 998/900 = 1:cm78< (100-10), 78/50 = 1:l28< (50-10), 28/10 = XX8< (100-1), 8/5 = 1:v
3< (5-1), 3/1 = 3:iiiret = MMMCMLXXVII
The code is as follows:
classsolution (object):defInttoroman (self, num):""": Type Num:int:rtype:str"""Map= [1000,900,500,400,100,90,50,40,10,9,5,4,1] Key= ['M','CM','D','CD','C','XC','L','XL','X','IX','V','IV','I'] RET="' forIinchRange (len (map)):ifNum >=Map[i]: Val= num/Map[i] ret+ = key[i]*Val Num-= map[i]*ValreturnRet
Integer to Roman