Java HashMap Solution


  • 3
    Z
    public class Solution {
    private static HashMap<Character, Integer> map = new HashMap<>();
    static{
        map.put('M', 1000);
        map.put('D', 500);
        map.put('C', 100);
        map.put('L', 50);
        map.put('X', 10);
        map.put('V', 5);
        map.put('I', 1);
    }
    public int romanToInt(String s) {
        int preVal = 0;
        int res = 0;
        for(int i = 0; i < s.length(); i++){
            int currVal = map.get(s.charAt(i));
            if(preVal < currVal){
                res -= preVal * 2;
            }
            preVal = currVal;
            res += currVal;  
        }
        return res;
    }
    

    }


  • 0
    W

    What about IIX?
    According to wikipedia, double subtraction is sometimes used.

    EDIT: for what reason people is down voting this reply?! Isn't this a natural thing to consider?


  • 0
    H

    so can u tell me what is XIIX?


  • 0
    W

    @Hangdra For sure it is 18, what else it can be?
    Actually, if you check the reference I gave. Your example is clearly mentioned:

    "Double subtractives" also occur, such as XIIX or even IIXX instead of XVIII. Sometimes V and L are not used, with instances such as IIIIII and XXXXXX rather than VI or LX.[8][9]

    Basically what I'm suggesting here is that to include the Roman number rule in the question, because not everyone is familiar/care about it, and there is some ambiguity in the system itself.


Log in to reply
 

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