Simple and concise Java solution


  • 0
    Z
    public int romanToInt(String s) {
            
            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 len = s.length();
           int result = 0;
           
           for(int i = 0; i < len; i++){
               int val1 = map.get(s.charAt(i));
               int val2 = 0;
               if( i + 1 < len ){
                   val2 = map.get(s.charAt(i+1));
               }
               
               if( val1 < val2 ){
                   result += val2 - val1;
                   i++;
               } else {
                   result += val1;
               }
           }
           
           return result;
    

Log in to reply
 

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