my java solution


  • 0
    C
    public class Solution {
    public int romanToInt(String s) {
        
        if(s.length() == 0)
            return 0;
        
        HashMap 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);
    
        if(s.length() == 1)
            return (Integer)map.get(s.charAt(0));
    
        int sum = 0;
        
        for(int i=0;i<s.length()-1;i++)
        {
            Integer current = (Integer)map.get(s.charAt(i));
            Integer next = (Integer)map.get(s.charAt(i+1));
            
            if(current>=next)
            {   
                sum=sum+current;
            }
            if(current < next)
            {
                sum=sum+next-current;
                i++;
            }
        }
        
        Integer current = (Integer)map.get(s.charAt(s.length()-2));
        Integer next = (Integer)map.get(s.charAt(s.length()-1));
        
        if(current >= next)
            return sum+next;
        else
            return sum;            
        
    }
    

    }


Log in to reply
 

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