思路:
1 将表达式转换成后缀表达式
2 利用栈计算后缀表达式
/** * 计算数值 * @param text * @return */ public static int count(String text) { Queue<String> queue=changeToPostOrder(text); Stack<Integer> stack=new Stack<>(); int result=0; while(!queue.isEmpty()) { String t=queue.poll(); if(t.length()>1)//数字 { stack.push(Integer.parseInt(t)); } else if(t.length()==1) { if(isYunsuanfu(t)) { char c=t.charAt(0); int ri=stack.pop(); int li=stack.pop(); switch (c) { case ‘+‘: result=li+ri; stack.push(result); break; case ‘-‘: result=li-ri; stack.push(result); break; case ‘*‘: result=li*ri; stack.push(result); break; case ‘/‘: result=li/ri; stack.push(result); break; default: break; } } else { stack.push(Integer.parseInt(t)); } } } return stack.empty()?0:stack.pop(); } //change to post order /** * 遇到数字直接输出,遇到符号,假如是高于栈顶优先级如乘除就直接压栈, * 假如是低于或等于栈顶优先级或者是右括号直接输出栈顶直到左括号,再压栈 * @param text * @return */ public static Queue<String> changeToPostOrder(String text) { Queue<String> queue=new LinkedList<>(); Stack<Character> stack=new Stack<>(); StringBuilder temp=new StringBuilder(); int len=text.length(); for(int i=0;i<len;i++) { char c=text.charAt(i); if (isNumber(c)) { temp.append(c); if(i==len-1) { queue.offer(temp.toString()); } }else { //如果是右括号 直接输出直到左括号 if(temp.length()!=0) { queue.offer(temp.toString()); temp.delete(0, temp.length()); } if(c==‘)‘) { while(stack.peek()!=‘(‘) { queue.offer(stack.pop()+""); } //弹出左括号 stack.pop(); continue; } //如果栈为空直接压栈 if(stack.empty() || c==‘(‘) { stack.push(c); continue; } //优先级比较 高优先级 压栈 while(!stack.empty() && !isHigher(c, stack.peek())) { queue.offer(stack.pop()+""); } stack.push(c); } } while(!stack.empty()) { queue.offer(stack.pop()+""); } return queue; } public static boolean isNumber(char c) { return c>=‘0‘ && c<=‘9‘; } public static boolean isYunsuanfu(String s) { return s.equals("*") || s.equals("/") || s.equals("+") || s.equals("-"); } public static boolean isHigher(char c,char cmp) { return priority(c)>priority(cmp); } public static int priority(char c) { int p=0; switch (c) { case ‘*‘: p=2; break; case ‘/‘: p=2; break; case ‘+‘: p=1; break; case ‘-‘: p=1; break; default: break; } return p; }
程序很罗嗦,有空再写一遍!
时间: 2024-10-09 01:52:09