-
Notifications
You must be signed in to change notification settings - Fork 9
/
EvaluateExpression.cpp
70 lines (66 loc) · 1.73 KB
/
EvaluateExpression.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
/*
Evaluate Expression
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
*/
// To evaluate postfix expression, if element is operator pop top two elements and push back the result, else push the value
int Solution::evalRPN(vector<string> &A) {
stack<int> nums;
for(auto a: A){
if(a == "+"){
int x=int(nums.top());
nums.pop();
int y=int(nums.top());
nums.pop();
nums.push(x+y);
}else if(a == "-"){
int x=int(nums.top());
nums.pop();
int y=int(nums.top());
nums.pop();
nums.push(y-x);
}else if(a== "*"){
int x=int(nums.top());
nums.pop();
int y=int(nums.top());
nums.pop();
nums.push(x*y);
}else if(a== "/"){
int x=int(nums.top());
nums.pop();
int y=int(nums.top());
nums.pop();
nums.push(y/x);
}else{
nums.push(stoi(a));
}
}
return nums.top();
}