-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path13.cpp
44 lines (35 loc) · 1 KB
/
13.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
// 13. Roman to Integer - https://leetcode.com/problems/roman-to-integer
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int romanToInt(string s) {
unordered_map<char, int> hashtable = {
{ 'I' , 1 },
{ 'V' , 5 },
{ 'X' , 10 },
{ 'L' , 50 },
{ 'C' , 100 },
{ 'D' , 500 },
{ 'M' , 1000 }
};
int sum = hashtable[s.back()];
for (int index = s.length() - 2; index >= 0; --index) {
if (hashtable[s[index]] < hashtable[s[index + 1]]) {
sum -= hashtable[s[index]];
} else {
sum += hashtable[s[index]];
}
}
return sum;
}
};
int main() {
ios::sync_with_stdio(false);
Solution solution;
assert(solution.romanToInt("DCXXI") == 621);
assert(solution.romanToInt("XXI") == 21);
assert(solution.romanToInt("IX") == 9);
assert(solution.romanToInt("III") == 3);
return 0;
}