Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
思路:
1.了解罗马字符与阿拉伯数字之间的关系;
String[] str = new String[] { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
int[] val = new int[] { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
2.显然,数字数组是按大到小排列的,而且罗马字符也是按大到小排序且是唯一的;
3 遍历罗马字符数组,使用while循环将给定字符串从头开始与其匹配,看重叠部分是否完全一致,如果一致,则将结果加到sum上,并且将字符串已匹配的部分删除,重复此操作,直到数组遍历完成
public int romanToInt(String s) {
String[] str = new String[] { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" };
int[] val = new int[] { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
if(s==null) return 0;
int len=s.length();
if(len==0) return 0;
int sum=0;
for(int i=0;i<str.length;i++){
while(s.length()>=str[i].length()&&str[i].equals(s.substring(0,str[i].length()))){
sum+=val[i];
s=s.substring(str[i].length());
}
}
return sum;
}