Simple Java Solution using HashMaps


  • 1
    R
    HashMap<Character, Integer> map = new HashMap<>();
            //Create the 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 len = s.length();
            int res = map.get(s.charAt(s.length() -1));
    
            for(int i = s.length() -2; i >= 0 ; i--){
                //If current letter is greater than or equal to next letter, add the value to the result
               // for example VI where V > I so ans is 5 + 1 = 6
                if(map.get(s.charAt(i)) >= map.get(s.charAt(i+1))){
                    res += map.get(s.charAt(i));
                }
                else{
                    // Similarly iV = 5 - 1 = 4 
                    res -= map.get(s.charAt(i));
                }
            }
            return res;

Log in to reply
 

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