Skip to content

Latest commit

 

History

History
34 lines (27 loc) · 700 Bytes

13. Roman to Integer.md

File metadata and controls

34 lines (27 loc) · 700 Bytes

13. Roman to Integer

Problem

Given a roman numeral, convert it to an integer.

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

tag:

Solution

java

    private static final Map<Character, Integer> map = 
        new HashMap<Character, Integer>() {{
            put('I', 1); put('V', 5); put('X',10);
            put('L', 5); put('C', 100); put('D',500);
            put('M', 1000); 
        }};
    public int romanToInt(String s) {
        int pre = 0, sum = 0;
        for(char c:s.toCharArray()) {
            int cur = map.get(c);
            sum += (cur>pre) ? (cur-2*pre) : cur; 
            pre = cur;
        }
        return sum;
    }

go