5-line C++ Solution, Easy to Understand


  • 0

    The idea is if some low value symbol appears before high value one, it means less not plus.

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

Log in to reply
 

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