求和栈 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
仅有 + - * /四则运算
可以看成无数个* / 运算后的结果的和
用一个栈来保存这个和
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static int calculate(String line) { Stack<Integer> toBeAdd = new Stack<>(); int num; char op = '+'; for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); //未雨绸缪,还没读到下个数先保存操作符 if("+-*/".contains(c+"")){ op = c; continue; } //数字和括号的匹配 int headIdx = i; if (Character.isDigit(c)) { while (i<line.length() && Character.isDigit(line.charAt(i))) i++; num = Integer.valueOf(line.substring(headIdx, i--)); } else { //括号表达式用递归处理,每次去掉一层括号 int level = 0; while(true){ //while循环找到这个左括号匹配的右括号,即处理((1+2)) , (1+2)+(3+4)等情况 if(line.charAt(i)=='(')level++; else if(line.charAt(i)==')'){ level--; if(level==0) break; } i++; } num = calculate(line.substring(headIdx+1,i)); } //根据之前保存的操作符进行操作 switch (op){ case '-': num = -num; break; case '*': num *= toBeAdd.pop();break; case '/': num = toBeAdd.pop() / num;break; } toBeAdd.add(num); } //求和 while(toBeAdd.size()!=1) toBeAdd.add(toBeAdd.pop()+toBeAdd.pop()); return toBeAdd.pop(); } public static void main(String[] args) { Scanner in = new Scanner(System.in); String line = in.nextLine(); System.out.println(calculate(line)); } }