Maybe a simple way...


  • 0
    S
    int romanToInt(string s) {
        map< char, int> list = {
            {'I', 1},
            {'V', 5},
            {'X', 10},
            {'L', 50},
            {'C', 100},
            {'D', 500},
            {'M', 1000}
        };
        int num = 0;
        int pre = 10000;
        for (int i=0; i<s.length(); i++){
            if (list[s[i]] > pre){
                num += list[s[i]] - pre*2;
            }
            else{
                num += list[s[i]];
            }
            pre = list[s[i]];
        }
        return num;
    }

Log in to reply
 

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