012 integer to roman

Given an integer, convert it to a roman numeral.

Input is guaranteed to be within the range from 1 to 3999.

思路

这一题需要我们把一个1-3999的整数,转换成罗马数字。

注意罗马数字的组成规则即可。1000是M,900是CM,500是D,400是CD。跨位不受影响。

举例:

1999是 MCMXCIX –> M/CM/XC/IX/

1876是 MDCCCLXXVI –> M/DCCC/LXX/VI/

罗马数字简直反人类,活该外国小朋友学不好数学哈哈哈哈哈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class (object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""
basics = ["I","II","III","IV","V","VI","VII","VIII","IX"]
res = ""
m = num / 1000
if (m > 0):
num = num - 1000 * m
for i in range(m):
res += "M"
if (num >= 900):
res += "CM"
num = num - 900
elif (num < 900 and num >= 500):
res += "D"
num = num - 500
elif (num >= 400 and num < 500):
res += "CD"
num = num - 400
c = num / 100
if ( c > 0 ):
num = num - 100 * c
for i in range(c):
res += "C"
if (num >= 90):
res += "XC"
num = num - 90
elif (num < 90 and num >= 50):
res += "L"
num = num - 50
elif (num >= 40 and num < 50):
res += "XL"
num = num - 40
x = num / 10
if ( x > 0 ):
num = num - 10 * x
for i in range(x):
res += "X"
if (num > 0):
res += basics[num-1]
return res