-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoman_class.cpp
More file actions
57 lines (48 loc) · 995 Bytes
/
Copy pathRoman_class.cpp
File metadata and controls
57 lines (48 loc) · 995 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
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
#include <unordered_map>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
class Roman
{
public:
string to_roman(int n);
int from_roman(string n);
};
string Roman::to_roman(int n)
{
int r1[13] = { 1000,900,500,400,100,90,50,40,10,9,5,4,1 };
string r2[13] = { "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I" };
string res;
for (int i =0 ; i < 13; i++)
{
while (n >= r1[i])
{
n -= r1[i];
res += r2[i];
}
}
return res;
}
int Roman::from_roman(string n)
{
unordered_map<char, int> roman{ {'M',1000}, {'D', 500},{'C', 100},{'L', 50}, {'X', 10}, {'V', 5}, {'I', 1} };
int sum = 0;
int prev = 0;
for (auto i : n)
{
int val = roman[i];
sum += (val < prev) ? -val : val;
prev = val;
}
return sum;
}
int main()
{
Roman RomanHelp;
cout << RomanHelp.to_roman(1000) << endl;
cout << RomanHelp.to_roman(1990) << endl;
cout << RomanHelp.from_roman("MCMXC") << endl;
cout << RomanHelp.from_roman("M") << endl;
}