-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevaluate-reverse-polish-notation.cpp
49 lines (47 loc) · 1.31 KB
/
evaluate-reverse-polish-notation.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
#include "header.h"
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack <string> S;
for(auto idx = tokens.begin(); idx != tokens.end(); idx++) {
string cur = *idx;
if((cur[0] >= '0' && cur[0] <= '9') || (cur[0] == '-' && cur.size() > 1)) {
S.push(cur);
}
else {
int a, b;
string sa, sb;
sb = S.top();
S.pop();
sa = S.top();
S.pop();
sscanf(sb.c_str(), "%d", &b);
sscanf(sa.c_str(), "%d", &a);
int temp;
switch(cur[0]) {
case '+':
temp = a + b;
break;
case '-':
temp = a - b;
break;
case '*':
temp = a * b;
break;
case '/':
temp = a / b;
break;
}
string sc = to_string(temp);
S.push(sc);
}
}
string last = S.top();
S.pop();
int ans;
sscanf(last.c_str(), "%d", &ans);
return ans;
}
};
int main() {
}