Friday, November 7, 2014

Facebook: Roman to Integer

Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
public class Solution {
    public int romanToInt(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        int result = 0;
        int i = 0;
        
        Map<String, Integer> map = constructMap();
        
        while (i < s.length()) {
            String curr = s.substring(i, i + 1);
            if ((curr.equals("C") || curr.equals("X") || curr.equals("I")) && (i < s.length() - 1)) {
                String temp = s.substring(i, i + 2);
                if (map.containsKey(temp)) {
                    result += map.get(temp);
                    i++;
                } else {
                    result += map.get(curr);
                }
            } else {
                result += map.get(curr);
            }
            i++;
        }
        
        return result;
    }
    
    private Map<String, Integer>constructMap() {
        Map<String, Integer> map = new HashMap<String, Integer>();
        
        map.put("M", 1000);
        map.put("CM", 900);
        map.put("D", 500);
        map.put("CD", 400);
        map.put("C", 100);
        map.put("XC", 90);
        map.put("L", 50);
        map.put("XL", 40);
        map.put("X", 10);
        map.put("IX", 9);
        map.put("V", 5);
        map.put("IV", 4);
        map.put("I", 1);
        
        return map;
    }
}

A neat solution:
public class Solution {
    public int romanToInt(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        
        int result = 0;
        int i = 0;
        
        Map<Character, Integer> map = constructMap();
        
        while (i < s.length()) {
            if (i < s.length() - 1 && map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) {
                result -= map.get(s.charAt(i));
            } else {
                result += map.get(s.charAt(i));
            }
            i++;
        }
        
        return result;
    }
    
    private Map<Character, Integer> constructMap() {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        
        map.put('M', 1000);
        map.put('D', 500);
        map.put('C', 100);
        map.put('L', 50);
        map.put('X', 10);
        map.put('V', 5);
        map.put('I', 1);
        
        return map;
    }
}

No comments:

Post a Comment