题解 | #牛的表达式计算器#
牛的表达式计算器
https://www.nowcoder.com/practice/261e7f01438f414c92f59c0059d3a906
题目考察的知识点 : 栈
题目解答方法的文字分析:
如果为数字,存入栈中即可
如果为操作符,取出栈中顶部两个元素进行计算,再将值存入栈中
本题解析所用的编程语言: java
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param tokens string字符串一维数组
* @return int整型
*/
public int calculatePostfix (String[] tokens) {
// write code here
Deque<Integer> stack = new ArrayDeque<>();
int digit;
for (String token : tokens) {
Integer res = 0;
if (token.equals("+")) {
res = stack.pop() + stack.pop();
} else if (token.equals("-")) {
digit = stack.pop();
res = stack.pop() - digit;
} else if (token.equals("*")) {
res = stack.pop() * stack.pop();
} else if (token.equals("/")) {
digit = stack.pop();
res = stack.pop() / digit;
} else {
res = Integer.parseInt(token);
}
stack.push(res);
}
return stack.peek();
}
}