Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
public static int romanToInt(String s) {
int num = 0, pre = 0;
int res = 0;
for (int i = s.length() - 1; i >= 0; i--) {
num = romateCharToNum(s.charAt(i));
if (pre > num) {
res -= num;
} else {
res += num;
}
pre = num;
}
return res;
}
static int romateCharToNum(char c) {
switch (c) {
case 'I':
return 1;
case 'X':
return 10;
case 'C':
return 100;
case 'M':
return 1000;
case 'V':
return 5;
case 'L':
return 50;
case 'D':
return 500;
}
return 0;
}