我似乎无法弄清楚为什么我的后缀计算器得到了错误的答案。
我的代码是:
public static int calcRPN(String[] postfix)
{
Stack<Integer> st = new Stack<Integer>();
String value;
int ans = 0;
for(int i = 0; i < postfix.length; i++){
value = postfix[i];
if (value.equals("+")) ans = st.push(st.pop() + st.pop());
else if (value.equals("-")) ans = st.push(st.pop() - st.pop());
else if (value.equals("*")) ans = st.push(st.pop() * st.pop());
else if (value.equals("/")) ans = st.push(st.pop() / st.pop());
else st.push(Integer.valueOf(value));
}
return ans;
}
输出:
Postfix: [4, 5, 7, 2, +, -, *], Answer: -16, Your answer: 16 ==> NO match...
Postfix: [3, 4, +, 2, *, 7, /], Answer: 2, Your answer: 0 ==> NO match...
Postfix: [5, 7, +, 6, 2, -, *], Answer: 48, Your answer: -48 ==> NO match...
Postfix: [4, 2, 3, 5, 1, -, +, *, +], Answer: 18, Your answer: 2 ==> NO match...
Postfix: [2, 3, *, 10, 4, /, -], Answer: 4, Your answer: -6 ==> NO match...
Postfix: [4, 23, 12, -, 2, *, +], Answer: 26, Your answer: -18 ==> NO match...
答案显然应该匹配。有任何想法吗?