Skip to content

Commit 299203b

Browse files
authored
Create Evaluate reverse polish notation.cpp
1 parent 43bba54 commit 299203b

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Evaluate reverse polish notation.cpp

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
private:
3+
long performedOperation(long operand1,long operand2,char op) {
4+
switch (op) {
5+
case '+':
6+
return operand1 + operand2;
7+
case '-':
8+
return operand1 - operand2;
9+
case '*':
10+
return operand1 * operand2;
11+
case '/':
12+
return operand1 / operand2;
13+
default:
14+
return 0;
15+
}
16+
}
17+
18+
bool isOperator(char ch) {
19+
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
20+
}
21+
22+
public:
23+
int evalRPN(vector<string>& tokens) {
24+
stack<long> Stack;
25+
for (const string& token : tokens) {
26+
if (token.size() == 1 && isOperator(token[0])) {
27+
long operand2 = Stack.top();
28+
Stack.pop();
29+
long operand1 = Stack.top();
30+
Stack.pop();
31+
Stack.push(performedOperation(operand1, operand2,token[0]));
32+
}
33+
else
34+
{
35+
Stack.push(stoi(token));
36+
}
37+
}
38+
39+
return Stack.top();
40+
41+
}
42+
};

0 commit comments

Comments
 (0)