My concise java solution


  • 1
    D

    The idea: use map to store the key(roman char)-value(integer), and loop the roman string from left to right to add each char's value to the result. If the previous char's smaller than the current char, the result shall subtract twice the previous char's value and then add the current char's value.

        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, pre, cur;
        total = map.get(s.charAt(0)); 
        
        for (int i = 1; i < s.length(); i++) {  
            pre = map.get(s.charAt(i - 1));  
            cur = map.get(s.charAt(i));  
    
            if (cur <= pre) {  
                total += cur;  
            } else {  
                total = total - pre * 2 + cur;  
            }  
        }
        return total;

Log in to reply
 

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