题目链接:https://leetcode.com/problems/roman-to-integer/
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
int Digit(char ch) {
int ret;
switch(ch) {
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;
}
}
int romanToInt(char* s) {
int ret = 0;
int i = strlen(s) - 1;
if(i >= 0)
ret = Digit(s[i]);
for(i = strlen(s) - 2; i >= 0; --i) { //从数组后向前遍历
if(Digit(s[i]) < Digit(s[i + 1]))
ret -= Digit(s[i]);
else
ret += Digit(s[i]);
}
return ret;
}