Problem
Roman numerals are represented by seven different symbols: I
, V
, X
, L
, C
, D
and M
.
1 | Symbol Value |
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.
Example 1:
1 | Input: "III" |
Example 2:
1 | Input: "IV" |
Example 3:
1 | Input: "IX" |
Example 4:
1 | Input: "LVIII" |
Example 5:
1 | Input: "MCMXCIV" |
Analysis
这题考察的是字符与数字之间的转换,与以往的题目不同,这次是要从罗马数字转为阿拉伯数字。罗马数字用的是字母来表示的,且他的表示方式是固定的,因此,我们可以通过建立一张转换表来进行换算。难点在于,部分字母连在一起所表达的意思是不同的。如IV
表示的是4,XL
表示的是40。这就需要我们特殊处理。
Solution
建立字符与数字的对应关系,很自然地想到了用map来实现。然后在遍历时特殊处理六种情况就可以了。
Code
1 | /* |
运行时间:约48ms,超过90.55%的CPP代码。
Summary
这道题目虽然很新,但是原理和字符数字转换的题目是一样的。只不过以往我们是基于ASCII的编码来进行转换,而这里需要我们人工定义转换的对应关系。弄懂了这个,整道题也就不难了。本题的题析到这里,谢谢您的支持!