LeetCode 第 150 题:逆波兰表达式求值
2023-03-03 本文已影响0人
放开那个BUG
1、前言

2、思路
遇到数字就入栈,遇到符号就出栈,然后将结果入栈
3、代码
class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<>();
for(String token : tokens){
if(token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")){
int num1 = Integer.parseInt(stack.pop()), num2 = Integer.parseInt(stack.pop());
if(token.equals("+")){
stack.push((num2 + num1) + "");
}
if(token.equals("-")){
stack.push((num2 - num1) + "");
}
if(token.equals("*")){
stack.push((num2 * num1) + "");
}
if(token.equals("/")){
stack.push((num2 / num1) + "");
}
}else{
stack.push(token);
}
}
return Integer.parseInt(stack.pop());
}
}