13. Roman to Integer

 

一、题目

  1、审题:

    

    2、分析:

      输入 1-3999 的罗马数字字符串,输出对应阿拉伯数字。

 

二、解答

  1、分析:

    字符串从左至右开始计算字符对应的阿拉伯数字,

    若比相邻右一个字符所对应的数字大,则加上此字符对应数字;

    若比相邻右一个字符所对应的数字小,则减去此字符对应的数字;

  

public class Solution {
    public int romanToInt(String s) {
         Map<String, Integer> map = new HashMap<String, 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 ret = 0;
        for(int index = 0; index < s.length() - 1; index++) {
            if(map.get(s.charAt(index) + "") < map.get(s.charAt(index + 1) + "")) {
                ret -= map.get(s.charAt(index) + "");
            }
            else {
                ret += map.get(s.charAt(index) + "");
            }
        }
        ret += map.get(s.charAt(s.length()-1) + "");
        return ret;
    }
}

 

posted @ 2018-08-02 08:58  skillking2  阅读(112)  评论(0编辑  收藏  举报