题解 | #表达式求值# 中缀 转 后缀,再计算后缀
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
/** 很传统的处理方式,但是我感觉考试的时候根本就写不完 */ import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Stack; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { private static int showPrio(Character c){ if(c.equals('*') || (c.equals('/'))){ return 1; }else if(c.equals('+') || (c.equals('-'))) { return 0; } return -1; } private static boolean ifPop(Stack<Character> s,Character c){ int a=0,b=0; if(s.empty()) return false; a=showPrio(s.peek()); b=showPrio(c); if(a==-1||b==-1) return false; return a>=b; } private static List<String> conv2postfix(String str) { char[] s = str.trim().toCharArray(); Stack<Character> stack = new Stack<>(); Character c; int num = 0; List<String> list = new ArrayList<>(); for (int i = 0; i < s.length; i++) { if (Character.isDigit(s[i])) { // System.out.print(s[i]); num = num * 10 + s[i] - '0'; if (i + 1 >= s.length || !Character.isDigit(s[i + 1])) { list.add(String.valueOf(num)); num = 0; } } else { if (s[i] == ')') { while ((c = stack.pop()) != '(') { // System.out.print(c); list.add(String.valueOf(c)); } continue; } //依次将栈中比它优先级高或等于它的操作符弹出并输出,然后将该操作符压入栈中。 while (ifPop(stack, s[i])) { // System.out.print(stack.pop()); list.add(String.valueOf(stack.pop())); } stack.push(s[i]); } } while (!stack.empty()) { // System.out.print(stack.pop()); list.add(String.valueOf(stack.pop())); } return list; } private static String calpostfix(List<String> list) { Stack<String> stack = new Stack<>(); list.stream().forEach(i-> { if (i.equals("/") || i.equals("*") || i.equals("+") || i.equals("-")) { int a = 0, b = 0; if (stack.size() >= 2) { b = Integer.valueOf(stack.pop()); a = Integer.valueOf(stack.pop()); } switch (i) { case "/": stack.push(String.valueOf(a / b)); break; case "*": stack.push(String.valueOf(a * b)); break; case "+": stack.push(String.valueOf(a + b)); break; case "-": stack.push(String.valueOf(a - b)); break; } } else { stack.push(i); } }); return stack.pop(); } public static void main(String args[]) { Scanner sc = new Scanner(System.in); StringBuffer sb=new StringBuffer(sc.nextLine()); //把一元运算符(正负号) 转化为 两个数做运算 for(int i=0;i<sb.length();i++){ if(sb.charAt(i)=='-' || sb.charAt(i)=='+'){ if(i-1<0 || sb.charAt(i-1)=='('){ sb.insert(i,'0'); } } } List<String> list = conv2postfix(sb.toString()); //list.stream().forEach(i->System.out.print(i+" ")); //System.out.println(""); System.out.println(calpostfix(list)); } }