My solution for JAVA! Easy understand!


  • 0
    D

    '''
    class Solution {
    public int romanToInt(String s) {
    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 result = 0;
      int n = s.length();
      int i = 0;
      while(i<n){
      if(i != s.length() - 1){
      if(map.get(s.charAt(i)) < map.get(s.charAt(i+1))){
      int mid = map.get(s.charAt(i+1)) - map.get(s.charAt(i));     
      result = result + mid;
      i = i+2;
      }else{
      result = result + map.get(s.charAt(i));
      i = i + 1;
      }        
      }else{
       
      result = result + map.get(s.charAt(s.length()-1));
      i = i + 1;
      }    
          
      }
      return result;
    }
    

    }
    '''


Log in to reply
 

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