Leetcode解题-Integer to Roman

描述

Given an integer, convert it to a roman numeral.

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

分析

要考虑罗马数字的加法规则和减法规则,要写对还是有一定技巧的,下面是一个精巧的解法。

代码

Python

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
class Solution(object):
def intToRoman(self, num):
"""
:type num: int
:rtype: str
"""

romans = [
('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
('V', 5),
('IV', 4),
('I', 1)
]
rs = []
for s, n in romans:
c, num = divmod(num, n)
rs.extend([s] * c)
return ''.join(rs)

热评文章