-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode-13-Roman_to_Integer.cpp
50 lines (42 loc) · 1.14 KB
/
leetcode-13-Roman_to_Integer.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <cstdlib>
#include <string>
#include <unordered_map>
class Solution {
public:
int romanToInt(std::string s) {
std::unordered_map<char, int> roman_vals =
{
{'I',1},
{'V',5},
{'X',10},
{'L',50},
{'C',100},
{'D',500},
{'M',1000}
};
size_t s_len = s.size(),
res = roman_vals[s[s_len-1]];
for(int i = (s_len-2); 0<=i; --i)
{
char current = s[i],
prev = s[i+1];
if(current == 'I' && (prev == 'V' || prev == 'X')) {
res -= roman_vals['I'];
} else if(current == 'X' && (prev == 'L' || prev == 'C')) {
res -= roman_vals['X'];
} else if(current == 'C' && (prev == 'D' || prev == 'M')) {
res -= roman_vals['C'];
} else {
res += roman_vals[current];
}
}
return res;
}
};
int main() {
std::string s = "III";
auto res = Solution().romanToInt(s);
std::cout << res << std::endl;
return EXIT_SUCCESS;
}