题目描述
计算逆波兰式(后缀表达式)的值
运算符仅包含"+","-","*“和”/",被操作数可能是整数或其他表达式
示例
解题思路
逆波兰表达式的解释器一般是基于堆栈的。
解释过程一般是:操作数入栈;遇到操作符时,操作数出栈,求值,将结果入栈;
当一遍后,栈顶就是表达式的值。
代码
import java.util.*;
public class Solution {
/**
*
* @param tokens string字符串一维数组
* @return int整型
*/
public int evalRPN (String[] tokens) {
if(tokens==null||tokens.length==0){
return 0;
}
Stack<Integer> stk = new Stack<>();
for (String s:tokens) {
if (s.equals("+")) {
int a = stk.pop();
int b = stk.pop();
stk.push(a+b);
}
else if (s.equals("-")) {
int a = stk.pop();
int b = stk.pop();
stk.push(b-a);
}
else if (s.equals("*")) {
int a = stk.pop();
int b = stk.pop();
stk.push(b*a);
}
else if (s.equals("/")) {
int a = stk.pop();
int b = stk.pop();
stk.push(b/a);
}
else {
stk.push(Integer.valueOf(s));
}
}
return stk.pop();
}
}
该博客介绍如何计算逆波兰式(后缀表达式)的值,涉及的运算符包括加、减、乘、除,内容包括解题思路和代码实现。
的值&spm=1001.2101.3001.5002&articleId=108798153&d=1&t=3&u=1242f7c5c7824a5ebfb71c7a245a5587)
1792

被折叠的 条评论
为什么被折叠?



