Java, scan from tail to head.


  • 0
    Z
    // scan from tail to head. 
    public int romanToInt(String s) {
        int ret = 0;
        int max = 0;
        
        for(int i = s.length() -1; i >=0; i --){
            int val = value(s.charAt(i));
            if(val >= max){
                max = val;
                ret += val;
            }else{
                ret -= val;
            }
        }
        
        return ret;
    }
    
    int value(char c){
        switch(c){
            case 'I':                return 1;
            case 'V':                return 5;
            case 'X':                return 10;
            case 'L':                return 50;
            case 'C':                return 100;
            case 'D':                return 500;
            case 'M':                return 1000;
        }
        
        throw new IllegalArgumentException();
    }

Log in to reply
 

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