Clean Java Solution


  • 0
    A
    public int romanToInt(String s) {
    	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 total = map.get(s.charAt(0));
    	
    	for (int i = 1; i < s.length(); i++) {
    		if (map.get(s.charAt(i)) > map.get(s.charAt(i - 1)))
    			total -= 2 * map.get(s.charAt(i - 1));  // subtract twice since added once before
    		total += map.get(s.charAt(i));
    	}
    	
    	return total;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.