package code;import java.util.Stack;public class Code227 {public int calculate(String s) {Stack<Integer> numSck=new Stack<Integer>();Stack<Character> opSck=new Stack<Character>();int i=0;s=s.replace(" ", "");int len=s.length();int result=0;while(i<len){char c=s.charAt(i);//numsif(c>='0' && c<='9'){int x=0;while(i<len && s.charAt(i)>='0' && s.charAt(i)<='9'){x*=10;x+=s.charAt(i)-'0';i++;}numSck.push(x);}//运算符else{if(c=='*' || c=='/'){while(!opSck.isEmpty() && (opSck.peek()=='*' || opSck.peek()=='/')){int a=numSck.pop();int b=numSck.pop();char op=opSck.pop();if(op=='*')b*=a;elseb/=a;numSck.push(b);}}else{while(!opSck.isEmpty()){int a=numSck.pop();int b=numSck.pop();char op=opSck.pop();if(op=='*')b*=a;else if(op=='/')b/=a;else if(op=='+')b+=a;elseb-=a;numSck.push(b);}}opSck.push(c);i++;}//如果处理完所有的字符,则对栈内运算if(i==len){while(!opSck.isEmpty()){int a=numSck.pop();int b=numSck.pop();char op=opSck.pop();if(op=='*')b*=a;else if(op=='/')b/=a;else if(op=='+')b+=a;elseb-=a;numSck.push(b);}if(!numSck.isEmpty())result=numSck.pop();elseresult=0;}}return result;}public static void main(String[] args){System.out.println(new Code227().calculate("1-1+1"));}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。