题目描述如下:
通过分析题目逻辑,罗马数字使用Map存储,调用String的CharAt方法提取字符串中的特定位置字符。
map.get(Object key):获取给定key对应的值;
char CharAt(int index):取字符串中存放在index位置的字符;
代码实现如下:
public static int romanToInt(String s){
if(s==null || s.length()==0)
return 0;
Map<Character,Integer> m = new HashMap<Character,Integer>();
m.put('I',1);
m.put('V',5);
m.put('X',10);
m.put('L',50);
m.put('C',100);
m.put('D',500);
m.put('M',1000);
int len=s.length();
int res = m.get(s.charAt(len-1));
for(int i=len-1;i>=1;i--){
//VI
if(m.get(s.charAt(i)) <= m.get(s.charAt(i-1))){
res += m.get(s.charAt(i-1));
}
//IV
else{
res -= m.get(s.charAt(i-1));
}
}
return res;
}