给你一个字符串数组 tokens
,表示一个根据 逆波兰表示法 表示的算术表达式。
请你计算该表达式。返回一个表示表达式值的整数。
示例 1:
输入:tokens = ["2","1","+","3","*"]
输出:9
解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9
示例 2:
输入:tokens = ["4","13","5","/","+"]
输出:6
解释:该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
java
import java.util.Stack;
public class title150 {
public static void main(String[] args) {
String[] tokens = {"2", "1", "+", "3", "*"};
System.out.println(evalRPN(tokens));
}
public static int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
Integer a, b, c;
for (int i = 0; i < tokens.length; i++) {
//1.先判断是否为四种符号
String s = tokens[i];
if (s.equals("+")) {
//需要将字符串形式的数字转化为int型
a = stack.pop();
b = stack.pop();
c = a + b;
stack.push(c);
} else if (s.equals("-")) {
a = stack.pop();
b = stack.pop();
c = b - a;
stack.push(c);
} else if (s.equals("*")) {
a = stack.pop();
b = stack.pop();
c = a * b;
stack.push(c);
} else if (s.equals("/")) {
a = stack.pop();
b = stack.pop();
c = b / a;
stack.push(c);
} else {
//先将字符串数字转换为int,再入栈
stack.push(Integer.valueOf(s));
}
}
return stack.pop();
}
}