Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
First need to know what is Roman numeral, and how it works
XXI,21
个位数举例
I,1 】II,2】 III,3】 IV,4 】V,5 】VI,6】 VII,7】 VIII,8 】IX,9
·十位数举例
X,10】 XI,11 】XII,12】 XIII,13】 XIV,14】 XV,15 】XVI,16 】XVII,17 】XVIII,18】 XIX,19】 XX,20】 XXI,21 】XXII,22 】XXIX,29】 XXX,30】 XXXIV,34】 XXXV,35 】XXXIX,39】 XL,40】 L,50 】LI,51】 LV,55】 LX,60】 LXV,65】 LXXX,80】 XC,90 】XCIII,93】 XCV,95 】XCVIII,98】 XCIX,99 】
·百位数举例
C,100】 CC,200 】CCC,300 】CD,400】 D,500 】DC,600 】DCC,700】 DCCC,800 】CM,900】 CMXCIX,999】
·千位数举例
M,1000】 MC,1100 】MCD,1400 】MD,1500 】MDC,1600 】MDCLXVI,1666】 MDCCCLXXXVIII,1888 】MDCCCXCIX,1899 】MCM,1900 】MCMLXXVI,1976】 MCMLXXXIV,1984】 MCMXC,1990 】MM,2000 】MMMCMXCIX,3999】
·千位数以上举例
-----
CLXXX DCL,183650】
====== -----
CXXXIV CMXLV DLXXXIV,134945584】
so there are two way to compute this problem:
1) in a case MDCCLXXXVIII
we need to compare adjacent two char, the first is M , the second is D
M = 1000, D = 500,
if M < D , which mean this two char stand for a integer
else one char stand for one integer
class Solution {
public:
int romanToInt(string s) {
int output = 0;
int val,val_1;
int size = s.size();
for (int i = 0; i < s.size(); i++){
val = fun(s[i]);
val_1 = fun(s[i+1]);
if (val < val_1){
output = val_1-val + output;
i++;//two char stand for one integer, that why i++ again
}
else{
output = output + val;
}
}
return output;
}
int fun(char a){
switch (a) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}
};
2)
class Solution {
public:
int romanToInt(string s) {
int res = 0;
int size = s.size();
int val_i, val_i_plus_1;
res += romanCharToInt(s[size-1]);
for (int i = 0; i < size-1; i++) {
val_i = romanCharToInt(s[i]);
val_i_plus_1 = romanCharToInt(s[i + 1]);
if ( val_i < val_i_plus_1) {
res -= val_i;
} else {
res += val_i;
}
}
return res;
}
inline int romanCharToInt(char c) {
switch (c) {
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default: return 0;
}
}