-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetCode150.cpp
40 lines (40 loc) · 1.06 KB
/
LeetCode150.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
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
stack<int> st;
int n = tokens.size();
for (int i = 0; i < n; i++)
{
if (tokens[i].size() > 1 or isdigit(tokens[i][0])) // isdigit works for single/digit only and >1 works for both negative numbers and numbers of multiple digits
{
st.push(stoi(tokens[i]));
}
else
{
int sec = st.top();
st.pop();
int fir = st.top();
st.pop();
int res;
if (tokens[i] == "+")
{
res = fir + sec;
}
else if (tokens[i] == "-")
{
res = fir - sec;
}
else if (tokens[i] == "*")
{
res = fir * sec;
}
else
res = fir / sec;
st.push(res);
}
}
return st.top();
}
};