A simple elegant C++ solution


  • 0
    A

    O(n), use a map to store the mapping, actually you can write a function to return the mapping, but I think that's tedious.

    int romanToInt(string s) {
        unordered_map<char, int> rimap= {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}};
        
        int res;
        
        for(int i = 0; i < s.size()-1; ++ i) {
            if(rimap[s[i+1]] > rimap[s[i]]) {
                res -= rimap[s[i]];
            }
            else {
                res += rimap[s[i]];
            }
        }
        
        res += rimap[s[s.size() - 1]];
        
        return res;
    }

Log in to reply
 

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