题目如下:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
题目的意思很明确,我们只要知道罗马数字的计算规则就可以写出这道题的答案了,直接看百度百科关于罗马数字的解释就可以,链接在这里:http://baike.baidu.com/link?url=XEX2--0UFdT7iFfq-S9gEARhOU_K9NdCOFR8FKlxcI8x-TbTih72er-vKRmoBsW5VebtxV9RuoVuE0bbICzxAK。代码也是比较简单,已Accepted的代码如下所示: public int romanToInt(String s) {
HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("I",1);
map.put("V",5);
map.put("X",10);
map.put("C",100);
map.put("M",1000);
map.put("L",50);
map.put("D",500);
int result = 0;
for(int i=0;i<s.length();i++){
int current = map.get(s.charAt(i)+"").intValue();
if(i<s.length()-1){
int next = map.get(s.charAt(i+1)+"").intValue();
result += next>current?current*(-1):current;
}else{
result += current;
}
}
return result;
}
评论区地址在这里:https://discuss.leetcode.com/category/21/roman-to-integer,大家有兴趣可以去看看