Simple Java solution


  • 0
    1
    class Solution {
        public int romanToInt(String s) {
            int result = 0;
            
            HashMap<Character, Integer> map = new HashMap<>();
            
            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 last = 0;
            
            for(int i = s.length()-1; i >= 0; i--) {
                
                Integer curr = map.get(s.charAt(i));
                
                if(curr >= last)
                    result += curr;
                else
                    result -= curr;
                
                last = curr;
                
            }
            
            return result;
        }
    }
    
    

Log in to reply
 

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