题目是比较简单,就是使用一个栈,每次遇到符号就计算就行了。但是在除法的时候注意除数为0的情况。还有就是除数与被除数的位置
public int evalRPN(String[] tokens) {
int result = 0;
Stack<String> stack = new Stack<>();
for (int i = 0; i < tokens.length; i++) {
if (!isOperator(tokens[i])) {
stack.push(tokens[i]);
} else {
String b = stack.pop();
String a = stack.pop();
String c = compute(a, tokens[i], b);
stack.push(c);
}
}
if (!stack.isEmpty()) {
String temp = stack.pop();
result = Integer.parseInt(temp);
}
return result;
}
public String compute(String str1, String op, String str2) {
int a = Integer.parseInt(str1);
int b = Integer.parseInt(str2);
int c = 0;
if (op.equals("+")) {
c = a + b;
} else if (op.equals("-")) {
c = a - b;
} else if (op.equals("*")) {
c = a * b;
} else if (op.equals("/")) {
if (a == 0) {
c = 0;
} else {
c = a / b;
}
}
return c + "";
}
public boolean isOperator(String str) {
boolean result = false;
if (str.equals("+")) {
result = true;
} else if (str.equals("-")) {
result = true;
} else if (str.equals("*")) {
result = true;
} else if (str.equals("/")) {
result = true;
}
return result;
}