letecode [13] - Roman to Integer
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.
Example 1:
Input: "III" Output: 3
Example 2:
Input: "IV" Output: 4
Example 3:
Input: "IX" Output: 9
Example 4:
Input: "LVIII" Output: 58 Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: "MCMXCIV" Output: 1994 Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
题目大意:根据输入的罗马数字,输出规则对应的相应整数。
理 解 :遍历输入的罗马数字,转化为整数值存于数组中。
遍历数组,若当前值比右边数大,则累加为和,i = i + 1;反之,则用右边的数-当前值,i = i + 2。(注意边界值的处理)
别人的解法:遍历罗马数字时,使用if进行比较,直接计算。这种效率从当前题目上看会高一点点,可不计。
代 码 C++:
class Solution { public: int romanToInt(string s) { int n = s.length(); int *arr = new int[n]; int i,value=0; for(i=0;i<n;++i){ switch(s[i]){ case 'I': arr[i] = 1; break; case 'V': arr[i] = 5; break; case 'X': arr[i] = 10; break; case 'L': arr[i] = 50; break; case 'C': arr[i] = 100; break; case 'D': arr[i] = 500; break; case 'M': arr[i] = 1000; break; } } for(i=0;i<n;++i){ if(i==n-1 || arr[i]>=arr[i+1]){ value = value + arr[i]; }else{ value = value + arr[i+1] - arr[i]; i++; } } return value; } };