题解 | #逆波兰表达式求值#
逆波兰表达式求值
https://www.nowcoder.com/practice/885c1db3e39040cbae5cdf59fb0e9382
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param tokens string字符串一维数组
* @return int整型
*/
public int evalRPN (String[] tokens) {
Stack<Integer> stack = new Stack<>();
// write code here
int sum = 0;
for (String c : tokens) {
// 判断c 并计算结果
sum = calc(c, stack);
stack.push(sum);
}
return stack.pop();
}
private int calc(String c, Stack<Integer> stack) {
int sum = 0;
if (c.equals("+")) {
// 这一步,需要考虑 谁是第一个变量,其实主要影响-和/
int b = stack.pop();
int a = stack.pop();
sum = a + b;
} else if (c.equals("-")) {
int b = stack.pop();
int a = stack.pop();
sum = a - b;
} else if (c.equals("*")) {
sum = stack.pop() * stack.pop();
} else if (c.equals("/")) {
int b = stack.pop();
int a = stack.pop();
sum = a / b;
} else {
sum = Integer.parseInt(c);
}
return sum;
}
}