您的位置:首页 > 编程语言 > Java开发

LeetCode 13 -Roman to Integer ( JAVA )

2016-04-10 19:45 495 查看
Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

public class Solution {
public int romanToInt(String s) {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);
int sum = map.get(s.charAt(s.length()-1));
for(int i=s.length()-1; i>0 ;i--){
if(map.get(s.charAt(i))>map.get(s.charAt(i-1))){
sum -= map.get(s.charAt(i-1));
}else{
sum += map.get(s.charAt(i-1));
}
}
return sum;
}
}



总结:本题只要知道对应的字符代表多少就行(然而我并不知道,参考的别人),把他们放入HashMap里面,如果大数在后就大数减去小数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: