罗马数字转整数

Posted on 2018-09-07 13:07  otonashi  阅读(104)  评论(0)    收藏  举报

给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。

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 length=s.length();
        int res=map.get(s.charAt(length-1));
        for(int i=length-2;i>=0;i--){
            if(map.get(s.charAt(i))>= map.get(s.charAt(i+1))){
                res += map.get(s.charAt(i));
            }
            else {
                res -= map.get(s.charAt(i));
            }
        }
                return res;
    }
}