【发布时间】:2014-10-30 19:19:52
【问题描述】:
在这个问题的输入中,有一个以后缀表示法给出的语句,我的任务是评估给定的语句。我完全理解算法,我将在下面发布我的解决方案。但由于某种原因,它适用于这些:1 2 3 * + 5 -、1 1 1 - - 1 + 1 +、1 2 + ... 等等,但是当有这样的多位数字时它不起作用一:100 20 -。我的解决方案(java):
public class PostFixEvaluation {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String expression = br.readLine();
char exp[] = expression.toCharArray();
ArrayStack<Integer> op = new ArrayStack<Integer>(100);
int vrednost = 0;
int dolzina = 0;
int suma = 0;
int res=0;
int convert = 0;
char ch;
for(int i=0; i < exp.length; i++){
ch = exp[i];
if(Character.isDigit(ch)){
convert = (int)ch-'0';
op.push(convert);
convert = 0;
}
else if(exp[i] == '+'){
int x = op.pop();
int y = op.pop();
vrednost = x + y;
op.push(vrednost);
vrednost = 0;
}
else if(exp[i] == '-'){
int x = op.pop();
int y = op.pop();
vrednost = y - x;
op.push(vrednost);
vrednost = 0;
}
else if(exp[i] == '*'){
int x = op.pop();
int y = op.pop();
vrednost = y * x;
op.push(vrednost);
vrednost = 0;
}
else if(exp[i] == '/'){
int x = op.pop();
int y = op.pop();
vrednost = y/x;
op.push(vrednost);
vrednost = 0;
}
}
res = op.pop();
System.out.println(res);
br.close();
}
}
【问题讨论】:
标签: java data-structures stack postfix-notation