-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0013-roman-to-integer.cpp
More file actions
29 lines (27 loc) · 972 Bytes
/
0013-roman-to-integer.cpp
File metadata and controls
29 lines (27 loc) · 972 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <algorithm>
#include <functional>
#include <string>
#include <map>
#include <vector>
class Solution {
public:
int romanToInt(std::string s) {
int result = 0;
std::vector<int> values = {1000, 500, 100, 50, 10, 5, 1};
std::vector<char> reprs = {'M', 'D', 'C', 'L', 'X', 'V', 'I'};
for (int i = 0; i < s.size(); i++) {
auto current_roman_index = std::find(reprs.begin(), reprs.end(), s[i]) - reprs.begin();
if (i + 1 < s.size()) {
auto next_roman_index = std::find(reprs.begin(), reprs.end(), s[i + 1]) - reprs.begin();
if (values[current_roman_index] < values[next_roman_index]) {
result -= values[current_roman_index];
}else {
result += values[current_roman_index];
}
}else {
result += values[current_roman_index];
}
}
return result;
}
};