Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
解:了解罗马数字组成规律,注意运行时间限制。
public class Solution {
public int romanToInt(String s) {
int i, total, pre, cur;
total = getValue(s.charAt(0));
pre = total;
for (i = 1; i < s.length(); i++) {
cur = getValue(s.charAt(i));
if (cur <= pre) {
total += cur;
} else { //total = total - pre + (cur - pre);
total = total - pre * 2 + cur;
}
pre = cur;
}
return total;
}
private int getValue(char a){
int b = 0;
switch (a){
case 'I':
b=1;break;
case 'X':
b=10;break;
case 'C':
b=100;break;
case 'M':
b=1000;break;
case 'V':
b=5;break;
case 'L':
b=50;break;
case 'D':
b=500;break;
default:
break;
}
return b;
}
}