Roman to Integer

public class Solution {
    private Map<Character, Integer> map = new HashMap<Character, Integer>(){
        {
            put('I', 1); put('V', 5); put('X', 10); put('L', 50); put('C', 100); put('D', 500); put('M', 1000);
        }
    };
    public int romanToInt(String str) {
        int result = 0;
        if (str.length() == 0) return result;

        for (int i = 0; i < str.length() - 1; ++i) {
            if (map.get(str.charAt(i)) < map.get(str.charAt(i + 1))) {
                result -= map.get(str.charAt(i));
            } else {
                result += map.get(str.charAt(i));
            }
        }

        result += map.get(str.charAt(str.length() - 1));

        return result;
    }
}

results matching ""

    No results matching ""