Skip to content

Commit 542afc8

Browse files
committed
#12. Integer to Roman
1 parent cb4b9de commit 542afc8

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

Others/int_to_roman.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Seven different symbols represent Roman numerals with the following values:
2+
3+
# Symbol Value
4+
# I 1
5+
# V 5
6+
# X 10
7+
# L 50
8+
# C 100
9+
# D 500
10+
# M 1000
11+
# Roman numerals are formed by appending the conversions of decimal place values
12+
# from highest to lowest. Converting a decimal place value into a Roman numeral
13+
# has the following rules:
14+
15+
# If the value does not start with 4 or 9, select the symbol of the maximal value
16+
# that can be subtracted from the input, append that symbol to the result, subtract
17+
# its value, and convert the remainder to a Roman numeral.
18+
# If the value starts with 4 or 9 use the subtractive form representing one symbol
19+
# subtracted from the following symbol, for example, 4 is 1 (I) less than 5 (V): IV
20+
# and 9 is 1 (I) less than 10 (X): IX. Only the following subtractive forms are
21+
# used: 4 (IV), 9 (IX), 40 (XL), 90 (XC), 400 (CD) and 900 (CM).
22+
# Only powers of 10 (I, X, C, M) can be appended consecutively at most 3 times
23+
# to represent multiples of 10. You cannot append 5 (V), 50 (L), or 500 (D) multiple
24+
# times. If you need to append a symbol 4 times use the subtractive form.
25+
# Given an integer, convert it to a Roman numeral.
26+
27+
28+
29+
# Example 1:
30+
31+
# Input: num = 3749
32+
33+
# Output: "MMMDCCXLIX"
34+
35+
# Explanation:
36+
37+
# 3000 = MMM as 1000 (M) + 1000 (M) + 1000 (M)
38+
# 700 = DCC as 500 (D) + 100 (C) + 100 (C)
39+
# 40 = XL as 10 (X) less of 50 (L)
40+
# 9 = IX as 1 (I) less of 10 (X)
41+
# Note: 49 is not 1 (I) less of 50 (L) because the conversion is based on decimal places
42+
# Example 2:
43+
44+
# Input: num = 58
45+
46+
# Output: "LVIII"
47+
48+
# Explanation:
49+
50+
# 50 = L
51+
# 8 = VIII
52+
# Example 3:
53+
54+
# Input: num = 1994
55+
56+
# Output: "MCMXCIV"
57+
58+
# Explanation:
59+
60+
# 1000 = M
61+
# 900 = CM
62+
# 90 = XC
63+
# 4 = IV
64+
65+
66+
# Constraints:
67+
68+
# 1 <= num <= 3999
69+
70+
71+
class Solution:
72+
def intToRoman(self, num: int) -> str:
73+
lists = [ ['M', 1000], ['CM', 900], ['D', 500], ['CD', 400], ['C', 100],
74+
['XC', 90], ['L', 50], ['XL', 40], ['X', 10], ['IX', 9], ['V', 5], ['IV', 4], ['I',1]]
75+
ans = []
76+
77+
for i in range(len(lists)):
78+
a = lists[i][0]
79+
b = lists[i][1]
80+
while num >= b:
81+
num -= b
82+
ans.append(a)
83+
return ''.join(ans)

0 commit comments

Comments
 (0)