[Leetcode C++] Roman to Integer


Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.


We traverse the string and add up each char by its value.
We need to handle a special case such as: IV, in which we have V-I = 4
In this case, we need to have I+V – 2*I = 4



class Solution {
    int romanToInt(string s) {
        if(s.empty()) return 0;
        unordered_map<char, int> map({{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50},  {'C', 100}, {'D', 500}, {'M', 1000}});
        int val = 0;
        for(int i=0; i<s.size(); i++){
            //Traverse and add the value
            val += map[s[i]];
            //Handle case like: IV = 4, as in the traverse we have added I(1) and V(5), we need to substract twice of I
            if(i>0 && map[s[i]] > map[s[i-1]])
                val -= 2*map[s[i-1]];
        return val;

Leave a Reply

Your email address will not be published. Required fields are marked *