Intuitive C++ solution


  • 0
    G

    See http://www.rapidtables.com/convert/number/how-roman-numerals-to-number.htm to understand how roman numerals are converted to numbers.

    class Solution {
        map<string,int> create_map() {
            map<string, int> r2i;
            r2i["I"] = 1;
            r2i["IV"] = 4;
            r2i["V"] = 5;
            r2i["IX"] = 9;
            r2i["X"] = 10;
            r2i["XL"] = 40;
            r2i["L"] = 50;
            r2i["XC"] = 90;
            r2i["C"] =  100;
            r2i["CD"] = 400;
            r2i["D"] = 500;
            r2i["CM"] = 900;
            r2i["M"] = 1000;
            return r2i;
        }
    public:
        int romanToInt(string s) {
            map<string, int> r_to_i = create_map();
            int i = 0, v = 0;
            while (i < s.size()) {
                map<string, int>::iterator it = r_to_i.find(s.substr(i, 1));
                int cur = 0;
                if (it != r_to_i.end()) cur = it->second;
                if (i + 1 < s.size()) {
                    map<string, int>::iterator it2 = r_to_i.find(s.substr(i, 2));
                    int cur2 = 0;
                    if (it2 != r_to_i.end()) cur2 = it2->second;
                    if (cur > cur2) i++;
                    else {
                        cur = cur2;
                        i += 2;
                    }
                } else i++;
                v += cur;
            }
            return v;
        }
    };
    

Log in to reply
 

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