My clean C++ solution


  • 4
    H
    class Solution {
    public:
            int romanToInt(string s) {
                std::map<char, int> table;
                table['I'] = 1;
                table['V'] = 5;
                table['X'] = 10;
                table['L'] = 50;
                table['C'] = 100;
                table['D'] = 500;
                table['M'] = 1000;
                int size = s.size(), res = 0;
                for(int i=0; i<size-1; i++) {
                    if(table[s[i]] >= table[s[i+1]]) {
                        res += table[s[i]];
                    }
                    else {
                        res -= table[s[i]];
                    }
                }
                return res + table[s[size-1]];
            }
    

    };


Log in to reply
 

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