-
Notifications
You must be signed in to change notification settings - Fork 15
/
evaluate-expression.cpp
35 lines (32 loc) · 972 Bytes
/
evaluate-expression.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
// Time - O(N), Space - O(N)
int Solution::evalRPN(vector<string> &A) {
int n = A.size();
unordered_map<string, bool> is_operator{{"+", true}, {"-", true}, {"*", true}, {"/", true}};
stack<int> operands;
for(int i = 0; i < n; i++) {
if(is_operator[A[i]]) {
int second = operands.top();
operands.pop();
int first = operands.top();
operands.pop();
int result;
if(A[i] == "+") {
result = first + second;
}
else if(A[i] == "-") {
result = first - second;
}
else if(A[i] == "*") {
result = first * second;
}
else if(A[i] == "/") {
result = first / second;
}
operands.push(result);
}
else {
operands.push(stoi(A[i]));
}
}
return operands.top();
}