【发布时间】:2018-03-27 12:22:11
【问题描述】:
所以我尝试为后缀评估方法编写代码,它给了我最离谱的结果。
我输入的后修复表达式是“92*3+4-”,根据我的计算,答案应该是 17。相反,我得到了 2849。这是怎么回事?
public static int postFixEvaluator(String s){
NewStack stack=new NewStack();
for(int i=0;i<s.length();i++){
if(Character.isDigit(s.charAt(i))) stack.push(s.charAt(i));
else if(s.charAt(i)=='+'){
int y=stack.pop();
int x=stack.pop();
int z=(int)(x+y);
stack.push((char)(z));
//System.out.println(z);
}
else if(s.charAt(i)=='-'){
int y=stack.pop();
int x=stack.pop();
int z=x-y;
stack.push((char)(z));
}
else if(s.charAt(i)=='*'){
int y=stack.pop();
int x=stack.pop();
int z=x*y;
stack.push((char)(z));
System.out.println(x*y);
}
else if(s.charAt(i)=='/'){
int y=stack.pop();
int x=stack.pop();
int z=x/y;
stack.push((char)(z));
}
else if(s.charAt(i)=='%'){
int y=stack.pop();
int x=stack.pop();
int z=x%y;
stack.push((char)(z));
}
}
return stack.pop();
}
enter code here
【问题讨论】:
标签: data-structures stack postfix-notation