原理:羅馬數字的比較,第i和第i+1的比較,s [i]<s[i+1] sum = sum-s[i];
s [i]>s[i+1] sum = sum+s[i];
注意字符串溢出!
public static int RomanToInteger(String s) {
int sum = 0;
for (int i = 0; i < s.length() - 1; i++) {
int a = StringToint(s.charAt(i));
int b = StringToint(s.charAt(i + 1));
if (a < b)
sum = sum - a;
else if (a >= b)
sum = sum + a;
}
return sum;
}
public static int StringToint(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;
}
return 0;
}