-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsolution150.cpp
More file actions
62 lines (56 loc) · 1021 Bytes
/
solution150.cpp
File metadata and controls
62 lines (56 loc) · 1021 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
58
59
60
61
62
/**
* Evaluate Reverse Polish Notation
*
* cpselvis([email protected])
* September 4th, 2016
*/
#include<iostream>
#include<stack>
#include<vector>
using namespace std;
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for (int i = 0; i < tokens.size(); i ++)
{
if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/")
{
st.push(atoi(tokens[i].c_str()));
}
else
{
int num1 = st.top();
st.pop();
int num2 = st.top();
st.pop();
int tmp;
if (tokens[i] == "+")
{
tmp = num2 + num1;
}
else if (tokens[i] == "-")
{
tmp = num2 - num1;
}
else if (tokens[i] == "*")
{
tmp = num2 * num1;
}
else if (tokens[i] == "/")
{
tmp = num2 / num1;
}
st.push(tmp);
}
}
return st.top();
}
};
int main(int argc, char **argv)
{
string arr[5] = {"2", "1", "+", "3", "*"};
vector<string> vec(arr + 0, arr + 5);
Solution s;
cout << s.evalRPN(vec) << endl;
}