【题目】
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
【解析】求罗马数字转换到int类型,考查的是HashMap或者二维数组的应用,以及string类型字符串的了解。
罗马数字只用于表示而不计算,4000以内有7种基本类型,按位相加。
string类型的输入,可以用s.getChar[i]获取第i位的字符,得到的是char类型。
在罗马数字中,如果某一位比其前一位小(如VI),则是直接加的关系;如果比前一位大(如IV),则需要考虑一下 。
【代码】
public class Solution {
public int romanToInt(String s) {
char[] symbol={'I','V','X','L','C','D','M'};
int[] result={1,5,10,50,100,500,1000};
Map<Character,Integer> romanmap= new HashMap<Character,Integer>();
int j = s.length();
for(int i=0;i<7;i++){
romanmap.put(symbol[i], result[i]);
}//for赋值
int res=0;
res+=romanmap.get(s.charAt(0));
for (int i = j-1; i >0; i--) {
int cur = romanmap.get(s.charAt(i));
int pre = romanmap.get(s.charAt(i - 1));
if (cur <= pre) {
res += cur;
} else {
res = res+ cur-2*pre;
}//if
}//for
return(res);
}
}