-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
150.cpp
83 lines (82 loc) · 2.47 KB
/
150.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
71
72
73
74
75
76
77
78
79
80
81
82
83
__________________________________________________________________________________________________
12ms
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
for(int i = 0; i < tokens.size(); ++i)
{
if(isdigit(tokens[i][0]) || (tokens[i][0] == '-' && isdigit(tokens[i][1])))
{
stk.push(atoi(tokens[i].c_str()));
}
else if(tokens[i][0] == '+')
{
int val1 = stk.top();
stk.pop();
int val2 = stk.top();
stk.pop();
stk.push(val2+val1);
}
else if(tokens[i][0] == '-')
{
int val1 = stk.top();
stk.pop();
int val2 = stk.top();
stk.pop();
stk.push(val2-val1);
}
else if(tokens[i][0] == '*')
{
int val1 = stk.top();
stk.pop();
int val2 = stk.top();
stk.pop();
stk.push(val2*val1);
}
else if(tokens[i][0] == '/')
{
int val1 = stk.top();
stk.pop();
int val2 = stk.top();
stk.pop();
stk.push(val2/val1);
}
}
return stk.top();
}
};
__________________________________________________________________________________________________
11244 kb
class Solution {
public:
int evalRPN(vector<string>& token) {
int i=0,a,b;
int end = token.size() - 1;
stack<int> stk;
while(i<=end)
{
//cout<<token[i]<<endl;
if((token[i] != "+") && (token[i] != "-") && (token[i] != "/") && (token[i] != "*"))
stk.push(stoi(token[i]));
else
{
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
if(token[i] == "+")
stk.push(a+b);
else if(token[i] == "/")
stk.push(b/a);
else if(token[i] == "-")
stk.push(b-a);
else
stk.push(a*b);
}
i++;
}
return stk.top();
}
};
__________________________________________________________________________________________________