My java solution using Map


  • 0
    Y
    public int romanToInt(String s) {
        int result = 0;
        Map<Character, Integer> romanMap = new HashMap<>();
        romanMap.put('I', 1);
        romanMap.put('V', 5);
        romanMap.put('X', 10);
        romanMap.put('L', 50);
        romanMap.put('C', 100);
        romanMap.put('D', 500);
        romanMap.put('M', 1000);
    
        int prevNum = romanMap.get(s.charAt(s.length() - 1));
        result = prevNum;
        for (int i = s.length() - 2; i >= 0 ; i--) {
            int currNum = romanMap.get(s.charAt(i));
            if (currNum >= prevNum) result += currNum;
            else result -= currNum;
            prevNum = currNum;
        }
    
        return result;
    }

Log in to reply
 

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