Ac solution code


  • 0
    /*   
     * The basic idea is as the following formula: 
     * 
     * if num[i+1] > num[i]
            result -= num[i]
       else
            result += num[i]
    
     * e.g. "DCXXI" = 621
     */ 
    public int  romanToInt(String s) {
        if (s == null || s.length() == 0)  return 0; 
        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 n = s.length(), res = map.get(s.charAt(n-1));// Must start from the end
        for (int i = n - 2; i >= 0; i--) {// Loop in the reverse order
            if (map.get(s.charAt(i+1)) > map.get(s.charAt(i)))  
                res -= map.get(s.charAt(i));
            else 
                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.