An uniform way to deal with all the circumstances, without complicated switchcase.


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

Log in to reply
 

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