题目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路:与12题正好相反,罗马数字基本字符集:I V X L C D M (1, 5, 10, 50, 100, 500, 1000)。思路是从字符串最低位开始匹配,累加相应字符对应的阿拉伯数字,要注意的就是I,X,L(1,10,100)要判断是在左还是在右,在左就减在右就加。判断方法是看累加值是否分别大于5,50,500
public class Solution {
public int romanToInt(String s) {
char[] arr=s.toCharArray();
int val=0;
for(int i=arr.length-1;i>-1;i--){
switch(arr[i]){
case 'I':val+=val>=5?-1 : 1;
break;
case 'V':val+=5;
break;
case 'X':val+=10*(val>=50?-1:1);
break;
case 'L':val+=50;
break;
case 'C':val+=100*(val>=500?-1:1);
break;
case 'D':val+=500;
break;
case 'M':val+=1000;
break;
}
}
return val;