class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> st;
for(string& s : tokens) {
if(s == "+" || s == "-" || s == "*" || s == "/") {
int b = st.top(); st.pop();
int a = st.top(); st.pop();
if(s == "+") st.push(a + b);
else if(s == "-") st.push(a - b);
else if(s == "*") st.push(a * b);
else st.push(a / b);
} else {
st.push(stoi(s));
}
}
return st.top();
}
};
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> st = new Stack<>();
for(String s : tokens) {
if(s.equals("+") || s.equals("-") ||
s.equals("*") || s.equals("/")) {
int b = st.pop();
int a = st.pop();
if(s.equals("+")) st.push(a + b);
else if(s.equals("-")) st.push(a - b);
else if(s.equals("*")) st.push(a * b);
else st.push(a / b);
} else {
st.push(Integer.parseInt(s));
}
}
return st.peek();
}
}
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
st = []
for token in tokens:
if token in ['+', '-', '*', '/']:
b = st.pop()
a = st.pop()
if token == '+':
st.append(a + b)
elif token == '-':
st.append(a - b)
elif token == '*':
st.append(a * b)
else:
# Python的除法需要特殊处理,确保结果向0取整
st.append(int(a / b))
else:
st.append(int(token))
return st[-1]