-
Notifications
You must be signed in to change notification settings - Fork 0
/
01.cpp
98 lines (72 loc) · 1.7 KB
/
01.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <sstream>
#include <string>
#include <iterator>
using namespace std;
string toString(int i)
{
std::stringstream ss;
ss << i;
return ss.str();
}
vector<string> SplitWithSpace(const string &source)
{
stringstream ss(source);
vector<string> vec( (istream_iterator<string>(ss)), istream_iterator<string>() );
return vec;
}
bool isOperator(string s) {
return (s == "+" || s == "-" || s == "*" || s == "/" || s == "%");
}
int cal(string op, int l, int r) {
if (op == "+")
return l + r;
else if (op == "-")
return l - r;
else if (op == "*")
return l * r;
else if (op == "/")
return l / r;
else if (op == "%")
return l % r;
else
return -1;
}
int main() {
string input;
bool il = false;
vector<string> ans;
while(getline(cin,input)){
if(input == ".") break;
vector<std::string> result = SplitWithSpace(input);
vector<string> stack;
for(int i = result.size() -1 ; i >= 0 ; i --) {
if(!isOperator(result[i])) {
// cout << "number : " << result[i] << endl;
stack.push_back(result[i]);
}
else {
// cout << stack.back() << endl;
if(stack.size() < 2) {
il = true; break;
}
int l = atoi(stack.back().c_str());
stack.pop_back();
int r = atoi(stack.back().c_str());
stack.pop_back();
int res = cal(result[i], l , r);
// cout << l << " " << result[i] << " " << r << " = " << res << endl;
stack.push_back(toString(res));
}
}
if(stack.size() > 1) il = true;
if(il) ans.push_back("illegal");
else ans.push_back(stack.back());
}
for(int i = 0 ; i < ans.size() ; i ++)
cout << ans[i] << endl;
return 0;
}