import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
String str = in.nextLine();
in.close();
int len = str.length();
int i=0,chtop=0,optop=0;
char ch;
char chs[] = new char[100];
char ops[] = new char[100];
chs[chtop] = '#';
ops[optop] = '#';
for(i=0;i<len;i++){
ch = str.charAt(i);
if(isOperator(ch)){
if(advance(ch) > advance(ops[optop])){
ops[++optop]=ch;
}else{
while(advance(ch)<=advance(ops[optop])){
chs[++chtop] = ops[optop--];
}
ops[++optop]=ch;
}
}else if(ch == '('){
ops[++optop]=ch;
}else if(ch == ')'){
while(ops[optop]!='('){
chs[++chtop]=ops[optop--];
}
optop--;
}else{
chs[++chtop]=ch;
}
}
while(ops[optop]!='#')
{
chs[++chtop]=ops[optop--];
}
int nums[] = new int[100];
int numtop = -1,result = 0;
for(i=1;i<=chtop;i++){
if(isOperator(chs[i])){
int b = nums[numtop--];
int a = nums[numtop--];
switch (chs[i]) {
case '+':
result = a+b;
break;
case '-':
result = a-b;
break;
case '*':
result = a*b;
break;
case '/':
result = a/b;
default:
break;
}
nums[++numtop]=result;
}else{
nums[++numtop]=chs[i]-'0';
}
}
System.out.print(result);
}
private static boolean isOperator(char ch) {
if(ch == '+' || ch == '-' || ch == '*' || ch =='/'){
return true;
}else {
return false;
}
}
private static int advance(char ch) {
if(ch=='+' || ch=='-') return 1;
else if(ch=='*' || ch=='/') return 2;
else if(ch == ')') return 3;
else return 0;
}
}
中缀表达式转后缀表达式并计算(十位以内)
最新推荐文章于 2022-11-08 23:29:57 发布