-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluate expression.txt
83 lines (62 loc) · 1.57 KB
/
evaluate expression.txt
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
Evaluate Expression
Problem Description
An arithmetic expression is given by a charater array A of size N. Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or operator.
Problem Constraints
1 <= N <= 105
Input Format
The only argument given is character array A.
Output Format
Return the value of arithmetic expression formed using reverse Polish Notation.
Example Input
Input 1:
A = ["2", "1", "+", "3", "*"]
Input 2:
A = ["4", "13", "5", "/", "+"]
Example Output
Output 1:
9
Output 2:
6
Example Explanation
Explaination 1:
starting from backside:
* : () * ()
3 : () * (3)
+ : (() + ()) * (3)
1 : (() + (1)) * (3)
2 : ((2) + (1)) * (3)
((2) + (1)) * (3) = 9
Explaination 2:
+ : () + ()
/ : () + (() / ())
5 : () + (() / (5))
1 : () + ((13) / (5))
4 : (4) + ((13) / (5))
(4) + ((13) / (5)) = 6
int Solution::evalRPN(vector<string> &A) {
int n=A.size();
stack<int> st;
for(int i=0;i<n;i++){
if(st.empty() or !(A[i]=="*" or A[i]=="/" or A[i]=="+" or A[i]=="-")){
st.push(stoi(A[i]));
}
else{
int s=st.top();
st.pop();
int f=st.top();
st.pop();
if(A[i]=="*")
st.push((f*s));
else if(A[i]=="+")
st.push((f+s));
else if(A[i]=="-"){
st.push((f-s));
}
else{
st.push((f/s));
}
}
}
return st.top();
}