Original Page: https://leetcode.com/problems/roman-to-integer/
Solutions
The description includes the example of 27. If the values are written from left to right in descending order, simply adding each number one by one will give the result.
XXVII
10(X) + 10(X) + 5(V) + 1(I) + 1(I) = 27
LVIII
50(L) + 5(V) + 1(I) + 1(I) + 1(I) = 58
But numbers like 4 and 9 are represented as a single number using two Roman numerals.
IV = 4
IX = 9
class Solution {
public:
int romanToInt(string s) {
int res = 0;
unordered_map<char, int> roman = {
{'I', 1},
{'V', 5},
{'X', 10},
{'L', 50},
{'C', 100},
{'D', 500},
{'M', 1000}
};
for (int i = 0; i < s.size() - 1; i++) {
if (roman[s[i]] < roman[s[i + 1]]) {
res -= roman[s[i]];
} else {
res += roman[s[i]];
}
}
return res + roman[s[s.size() - 1]];
}
};