Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
这道题要知道罗马数字的计算规则:
1,I, V, X, L, C, D, M 分别对应 1, 5,10,50,100,500,1000.
2,IV 表示 4,即5-1, VI表示6,即5+1.
难点在于,怎么判断IV,这里采取一种简单地逻辑,即碰见 I 就先加 1,等碰见 V 的时候,检查前一位是否比 V 小, 看见是 I,则说明是 IV, 应该是 5-1,但由于前面已经加了 1,应该把之前的 1 也减去,所以应该是 5 - 2*1. 以此类推。
public class Solution {
public int romanToInt(String s) {
int result = 0;
for(int i=0; i<s.length(); i++){
if( i > 0 && c2n(s.charAt(i)) > c2n(s.charAt(i-1)) )
//如果当前值比前一个大,则应该减去前一个值,比如IV,但由于之前I已经加过,
//所以要减两次
result += c2n(s.charAt(i)) - 2*c2n(s.charAt(i-1));
else
result += c2n(s.charAt(i));
}
return result;
}
public int c2n(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;
}
}
}