-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathRoman-To-Integer.cpp
66 lines (63 loc) · 1.61 KB
/
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/// Source : https://leetcode-cn.com/problems/roman-to-integer/
/// Author : bryce
/// Time : 2019-11-04
#include <iostream>
#include <string>
#include <tr1/unordered_map>
using namespace std;
using namespace std::tr1;
//C++ Solution 1: 利用哈希表查找
class Solution {
public:
int romanToInt(string s) {
int res = 0;
int n = s.size();
unordered_map<char, int> words;
words['I'] = 1; words['V'] = 5;
words['X'] = 10; words['L'] = 50;
words['C'] = 100; words['D'] = 500;
words['M'] = 1000;
for (int i = 0; i < n; i++) {
int val = words[s[i]];
if (i != n - 1 && words[s[i+1]] > words[s[i]])
{
res += words[s[i+1]] -words[s[i]];
i++;
}
else
res += val;
}
return res;
}
};
//C++ Solution 2:
class Solution {
public:
int romanToInt(string s) {
int res = 0;
int n = s.size();
int flag[256] = {0};
flag['I'] = 1; flag['V'] = 5;
flag['X'] = 10; flag['L'] = 50;
flag['C'] = 100; flag['D'] = 500;
flag['M'] = 1000;
for (int i = 0; i < n; i++) {
int val = flag[s[i]];
if (i != n - 1 && flag[s[i+1]] > flag[s[i]])
{
res += flag[s[i+1]] - flag[s[i]];
i++;
}
else
{
res += val;
}
}
return res;
}
};
int main()
{
cout << Solution().romanToInt("CDI") << endl;
return 0;
}