Roman to Integer

Desicription

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
private:
unordered_map<char, int> mp = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
public:
int romanToInt(string s) {
int res = mp[s[0]];
for(int i = 1; s[i]; i++){
if(mp[s[i]] > mp[s[i-1]])
res += mp[s[i]] - mp[s[i-1]] * 2;
else
res += mp[s[i]];
}
return res;
}
};