-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.cpp
More file actions
76 lines (70 loc) · 1.79 KB
/
stack.cpp
File metadata and controls
76 lines (70 loc) · 1.79 KB
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
#include <bits/stdc++.h>
// 空白区切り、1行の数式を取得する
std::vector<std::string> GetInputFormula()
{
std::vector<std::string> vecstr;
std::string r, s;
std::getline(std::cin, r);
std::stringstream ss; // std::stringstream ss{r}だとエラー
ss << r;
while (getline(ss, s, ' '))
{
vecstr.push_back(s);
}
return vecstr;
}
// 逆ポーランド記法の数式を
// std::stackを用いて計算する
// 数値→スタックに積む
// 演算子→スタックから2つ取り出して演算
// を繰り返す
void CalcRPNbyStack(std::vector<std::string> vecstr)
{
std::stack<int> results;
for (std::string v : vecstr)
{
try
{
int num = std::stoi(v);
results.push(num);
}
catch (const std::invalid_argument &e)
{
int num1 = results.top();
results.pop();
int num2 = results.top();
results.pop();
if (v == "+")
{
int res = num2 + num1;
results.push(res);
}
else if (v == "-")
{
int res = num2 - num1;
results.push(res);
}
else if (v == "*")
{
int res = num2 * num1;
results.push(res);
}
// 今回は割り算は対象ではないが一応
else if (v == "/")
{
int res = num2 / num1;
results.push(res);
}
}
}
std::cout << results.top() << std::endl;
}
int main()
{
static const int MAX = 1000000;
int n, R[MAX];
std::string r, s;
std::vector<std::string> vecstr = GetInputFormula();
CalcRPNbyStack(vecstr);
return 0;
}