题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.Scanner; import java.util.Stack; import java.io.InputStream; import java.io.PrintStream; import java.io.IOException; public class Main { public static void main(String[] args) { InputStream inpts=System.in; Scanner in = new Scanner(inpts); String calStr=in.nextLine(); try{ inpts.close(); }catch(IOException e){ e.printStackTrace(); } in.close(); char c='\u0000'; int i=0; int n=calStr.length(); int t=0; int j=0; int nums[][]=new int[n][2];//存放字符串中数字对应的值和索引 boolean bn1=false; for(;i<n;++i){ c=calStr.charAt(i); if((c-'0'|'9'-c)>0){ t*=10; t+=c-48; bn1=true; }else if(bn1){ nums[j][0]=t; nums[j++][1]=i-1; t=0; bn1=false; } } nums[j][0]=t; nums[j++][1]=i-1; float res=calculate(calStr,nums); PrintStream pt=System.out; pt.println((int)res); pt.close(); } public static float calculate(String s,int num[][]){ Stack<Character> symbol=new Stack<>(); Stack<Float> number=new Stack<>(); int i=0; int j=0; int n=s.length(); char c='\u0000'; char cTmp='\u0000'; float m=0; for(;i<n;++i){ c=s.charAt(i); if((c-'0'|'9'-c)>0){ m=num[j][0]; number.push(m); i=num[j++][1]; }else if(c=='('||c=='['||c=='{'){ symbol.push('('); }else if(c==')'||c==']'||c=='}'){ cTmp=symbol.peek(); while(cTmp!='('){ twoNumRes(number,symbol); cTmp=symbol.peek(); } symbol.pop(); }else{ cTmp=s.charAt(i-1); if(i==0||i>0&&(cTmp=='('||cTmp=='['||cTmp=='{')){ number.push(0f); } while(!symbol.isEmpty()&&symbol.peek()!='('){ cTmp=symbol.peek(); if(canCalFirst(c,cTmp)){ twoNumRes(number,symbol); }else{ break; } } symbol.push(c); } } while(!symbol.isEmpty()){ twoNumRes(number,symbol); } return number.peek(); } public static void twoNumRes(Stack<Float> num,Stack<Character> sym){ float b=num.pop(); float a=num.pop(); char cs=sym.pop(); float res=0f; if(cs=='+'){ res=a+b; }else if(cs=='-'){ res=a-b; }else if(cs=='*'){ res=a*b; }else{ res=a/b; } num.push(res); } public static boolean canCalFirst(char c0,char cTop){ if((c0=='*'||c0=='/')&&(cTop=='+'||cTop=='-')){ return false; } return true; } }