Integer to Roman
description:
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
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 beforeV
(5) andX
(10) to make 4 and 9.X
can be placed beforeL
(50) andC
(100) to make 40 and 90.C
can be placed beforeD
(500) andM
(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.
Example 1:
Input: 3
Output: "III"
Example 2:
Input: 4
Output: "IV"
Example 3:
Input: 9
Output: "IX"
题意很简单,输入一个数字,返回它的罗马数字,数据范围在1~3999。罗马数字大多数采用往右边加的形式表示,但有一些例外采用放到左边减掉的形式,以免显得冗余。比如4:IV,9:IX,40:XL,90:IC,400:CD,900:CM
。发现他们模10或100后都是4,9。于是可以采用分类的方法求解。
解法一:由于题目数据范围较小,可以把特殊的数字和罗马数字用数组或列表表示出来,一一映射,然后遍历列表,大于某一个数时,把对应的罗马数字加入到字符串同时减掉那个数值。
Mycode1:
class Solution:
def intToRoman(self, num: int) -> str:
values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
Rom = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
ans = ''
for _ in range(len(values)):
while num >= values[_]:
ans += Rom[_]
num -= values[_]
return ans
解法二:
这种解法相应可以处理较大的数据范围,把主要的数字和罗马数字用列表表示,遍历列表,每次以模的范式处理,然后分类讨论拼接字符串。这种写法相对麻烦,容易写错,可以在写代码的时候配合自己想的一个样例然后去处理这些细节,当然主要还是我的代码能力太低了哈哈。
Mycode2:
class Solution:
''' 1842
M 842
MDCCC 42
MDCCCXL 2
MDCCXLII 0
'''
def intToRoman(self, num: int) -> str:
values = [1000, 500, 100, 50, 10, 5, 1]
Rom = ['M', 'D', 'C', 'L', 'X', 'V', 'I']
ans = ''
for i in range(0, len(values), 2):
tem = num // values[i]
if tem < 4:
for _ in range(tem):
ans += Rom[i]
#print(ans, end=' ')
elif tem == 4:
#拼接字符串,顺序不可变
ans = ans + Rom[i] + Rom[i-1]
#print(ans, end=' ')
elif tem > 4 and tem < 9:
ans += Rom[i-1]
for _ in range(tem-5):
ans += Rom[i]
#print(ans, end=' ')
elif tem == 9:
ans = ans + Rom[i] + Rom[i-2]
#print(ans, end=' ')
num %= values[i]
#print(num)
return ans
谢谢你的观看!