Roman to Integer
Last updated
Last updated
Input: s = "III"
Output: 3
Input: s = "IV"
Output: 4
Input: s = "IX"
Output: 9
Input: s = "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.#include <map>
class Solution
{
map<char,int> rtoi =
{
{'I',1},
{'V',5},
{'X',10},
{'L',50},
{'C',100},
{'D',500},
{'M',1000},
};
public:
int romanToInt(string s)
{
unsigned res = 0;
for(size_t i = 0; i < s.size(); ++i)
{
if(i != s.size()-1)
{
if(s[i] == 'I' && (s[i+1] == 'V' || s[i+1] == 'X') ||
s[i] == 'X' && (s[i+1] == 'L' || s[i+1] == 'C') ||
s[i] == 'C' && (s[i+1] == 'D' || s[i+1] == 'M') )
{
res+=rtoi[s[i+1]] - rtoi[s[i]];
++i; //we processed 2 symbols
continue;
}
}
res+=rtoi[s[i]];
}
return res;
}
};