LeetCode 13. Roman to Integer

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