题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
先中缀表达式转后缀表达式,然后计算。
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String str=in.nextLine();
str=str.replace('[','(');//把所有中括号大括号转成小括号,便于后面中缀表达式转后缀表达式的处理
str=str.replace(']',')');
str=str.replace('{','(');
str=str.replace('}',')');
Stack<String> op=new Stack<String>();//运算符栈
Stack<String> res=new Stack<String>();//后缀表达式栈
int ii=0;
while(ii<str.length()){
StringBuffer sb=new StringBuffer();
Character temp=str.charAt(ii);
if(temp>='0'&&temp<='9'){//数字直接压入后缀表达式栈
while(ii<str.length()&&str.charAt(ii)>='0'&&str.charAt(ii)<='9'){
sb.append(str.charAt(ii));
ii++;
}
res.push(sb.toString());
}
else if(temp=='('){//左括号直接压入运算符栈
op.push(temp.toString());
ii++;
}
else if(temp==')'){//右括号,运算符栈弹栈,直到栈顶是左括号(左括号也弹出)
String t=op.pop();
while(t.charAt(0)!='('){
res.push(t);
t=op.pop();
}
ii++;
}
else{//+、-、*、/的情况
StringBuffer sb1=new StringBuffer();
if(((ii==0)||(ii>0&&(str.charAt(ii-1)=='(')))&&(temp=='+'||temp=='-')&&(str.charAt(ii+1)>='0'&&str.charAt(ii+1)<='9')){//如果是负数,把这个负数提取出来压入后缀表达式栈
sb1.append(temp);
ii++;
while(ii<str.length()&&str.charAt(ii)>='0'&&str.charAt(ii)<='9'){
sb1.append(str.charAt(ii));
ii++;
}
res.push(sb1.toString());
}
else{//如果就单纯是一个运算符,如果他的优先级小于栈顶元素,弹栈,直到栈为空或栈顶为左括号或者栈顶元素优先级小于当前运算符
while(!op.isEmpty()&&op.peek().charAt(0)!='('&&compare(op.peek().charAt(0),temp)){
String t=op.pop();
res.push(t);
}
op.push(temp.toString());
ii++;
}
}
}
while(!op.isEmpty()){//如果操作符栈不为空,则依次压入后缀表达式栈
res.push(op.pop());
}
int[] r=new int[str.length()];
int top=0;
for(String i:res){//遍历这个后缀表达式
if(i.charAt(0)>='0'&&i.charAt(0)<='9'){//如果是正数,直接压栈
r[top++]=Integer.parseInt(i);
}
else if(i.length()>1){//如果数字前面有正负号
if(i.charAt(0)=='+'){
r[top++]=Integer.parseInt(i.substring(1));
}
else if(i.charAt(0)=='-'){
r[top++]=Integer.parseInt(i.substring(1))*(-1);
}
}
else{//如果是运算符,弹出两个数字,计算结果并再压入栈中
int x=r[--top];
int y=r[--top];
r[top++]=operator(y,x,i.charAt(0));
}
}
System.out.println(r[0]);
}
}
public static boolean compare(char ch1,char ch2){
if(ch1=='*'||ch1=='/'){
return true;
}
if((ch1=='+'||ch1=='-')&&(ch2=='+'||ch2=='-')){
return true;
}
return false;
}
public static int operator(int x,int y,Character op){
if(op=='+'){
return x+y;
}
else if(op=='-'){
return x-y;
}
else if(op=='*'){
return x*y;
}
else{
return x/y;
}
}
}
