-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluate_expression.cpp
More file actions
88 lines (76 loc) · 1.79 KB
/
Copy pathevaluate_expression.cpp
File metadata and controls
88 lines (76 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
77
78
79
80
81
82
83
84
85
86
87
88
/*
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Input Format
The only argument given is character array A.
Output Format
Return the value of arithmetic expression formed using reverse Polish Notation.
For Example
Input 1:
A = ["2", "1", "+", "3", "*"]
Output 1:
9
Explaination 1:
starting from backside:
*: ( )*( )
3: ()*(3)
+: ( () + () )*(3)
1: ( () + (1) )*(3)
2: ( (2) + (1) )*(3)
((2)+(1))*(3) = 9
Input 2:
A = ["4", "13", "5", "/", "+"]
Output 2:
6
Explaination 2:
+: ()+()
/: ()+(() / ())
5: ()+(() / (5))
1: ()+((13) / (5))
4: (4)+((13) / (5))
(4)+((13) / (5)) = 6
*/
#include<iostream>
#include<cstdlib>
#include<stack>
#include<vector>
#include<cstring>
using namespace std;
int evaluateExpression(vector<string> exp)
{
stack<int> s;
for(int i=0;i<exp.size();i++)
{
if(exp[i]=="-" || exp[i]== "+" || exp[i]=="*" || exp[i]=="/" || exp[i]=="^")
{
int op1=s.top();
s.pop();
int op2=s.top();
s.pop();
if(exp[i]=="-")
s.push(op1-op2);
else if(exp[i]=="+")
s.push(op1+op2);
else if(exp[i]=="*")
s.push(op1*op2);
else if(exp[i]=="/")
{
if(op2!=0)
s.push(op1/op2);
}
else if(exp[i]=="^")
s.push(op1^op2);
}
else
{
s.push(atoi(exp[i].c_str()));
}
}
return s.top();
}
int main()
{
vector<string> exp={"2", "1", "+", "3", "*"};
cout<<evaluateExpression(exp)<<endl;
return 0;
}