[leetocde] Roman to Integer

Roman to Integer

从右往左计算

class Solution {
public:
    int romanToInt(string s) {

        int res=0;
        int len=s.length();
        if(len<=0){
            return res;
        }
        
        map<char,int> rti;
        rti['I']=1;
        rti['V']=5;
        rti['X']=10;
        rti['L']=50;
        rti['C']=100;
        rti['D']=500;
        rti['M']=1000;
        
        res=rti[s[len-1]];
        for(int i=len-2;i>=0;i--){
            if(rti[s[i]]>=rti[s[i+1]]){
                res+=rti[s[i]];
            }else{
                res-=rti[s[i]];
            }

        }
        return res;
    }
};


你可能感兴趣的:([leetocde] Roman to Integer)