# Roman to Integer

• A simple solution O(n) complexity solution is to traverse the input string and add integer values of roman letters to final answer. By the time traversal reaches end of string it will have the equivalent integer value. However, one important point is to keep in mind is the way roman letters are arranged, if roman letter having less integer value (e.g. I) precedes a letter having bigger integer value (e.g. V) then I (=1) should be substracted from V (=5) before adding to final answer. A map can be used for mapping from roman alphabets to numbers. A sample program is shown below.

``````class Solution {
map<char, int> rtoi = map<char, int>({
{'M',1000},
{'D',500},
{'C',100},
{'L', 50},
{'X', 10},
{'V', 5},
{'I',1}
});
public:

int romanToInt(string s) {
if(s==string(""))
return 0;

int num=0, i=0;
for(i=0;i<s.length()-1;i++)
{
if(rtoi[s[i]] < rtoi[s[i+1]])
{
num+=(rtoi[s[i+1]]-rtoi[s[i]]);
i++;
}
else
num+=rtoi[s[i]];
}
num+=rtoi[s[i]];
return num;
}
};
``````

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