Friday, May 5, 2017

13. Roman to Integer

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.


Solution:

We can add from left to right.

We only need to worry when the left number is less than the right number.

If we find the number at index i is larger than the number at index i - 1, we know we should minus the number in index i instead of adding it.

So we minus it twice to cancel the operation that it adds in previous round.



Code:


public class Solution {
    public int romanToInt(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        Map<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 result = map.get(s.charAt(0));
        for (int i = 1; i < s.length(); i++) {
            result += map.get(s.charAt(i));
            if (map.get(s.charAt(i - 1)) < map.get(s.charAt(i))) {
                result -= map.get(s.charAt(i - 1)) * 2;
            }
        }
        return result;
    }
}