题目要求
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 a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
题目分析及思路
给一个罗马数字,要求得到它对应的整数。罗马数字与整数的对应关系是:'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000。罗马数字从左到右依次减小。需要考虑三种特殊情况:1)IV:4,IX:9;2)XL:40,XC:90;3)CD:400,CM:900。可以建一个字典存储这些罗马数字,之后可获得给定罗马数字各位所对应的整数列表,然后遍历这个列表,若右边的数字大于左边的数字,则需要加上右边的数字再减去两倍左边的数字;否则直接加上右边的数字。
python代码
class Solution:
def romanToInt(self, s: str) -> int:
d = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
l = [d[i] for i in s]
ans = l[0]
for idx in range(1,len(l)):
if l[idx]>l[idx-1]:
ans += (l[idx]-2*l[idx-1])
else:
ans += l[idx]
return ans