题解 | #四则运算#抄的大佬作业
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { /** * 输入一个表达式(用字符串表示),求这个表达式的值。 * 保证字符串中的有效字符包括[‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。且表达式一定合法。 * 输入:3+2*{1+2*[-4/(8-6)+7]} * 输出:25 * * @param args */ public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { String str = in.nextLine(); str = str.replaceAll("\\[", "("); str = str.replaceAll("\\{", "("); str = str.replaceAll("]", ")"); str = str.replaceAll("}", ")"); int v = compute(str); System.out.println(v); } } public static int compute(String str) { char[] chars = str.toCharArray(); Stack<Integer> stack = new Stack<>();//保存已计算好的结果 int num = 0; char sign = '+'; for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (Character.isDigit(c)) { num = num * 10 + (c - '0');//如果125,依次1,1*10+2=12,12*10+5 = 125; } if (c == '(') {//遇到左括号 需要递归求出括号内值 int count = 1;//记录该括号的终点);遇左括号+1,遇右括号-1,=0时 即完整括号的右边界 int j = i + 1;//记录该括号的长度 while (count > 0) { if (chars[j] == '(') count++; if (chars[j] == ')') count--; j++; } num = compute(str.substring(i + 1, j - 1)); i = j - 1;//计算完后更新索引(跳过计算完成的括号) } if (!Character.isDigit(c) || i == chars.length - 1) { if (sign == '+') stack.push( num);//上一个符号是加号,直接把操作数入栈 else if (sign == '-') stack.push(-1 * num); else if (sign == '*') stack.push(stack.pop() * num); // 上一个符号是乘号,把乘号前面的操作数取出来进行计算再入栈 else if (sign == '/') stack.push(stack.pop() / num); sign = c;// 把符号更新为当前符号 num = 0;//本次num已入栈 置零 下次使用 } } int sum = 0; while (!stack.isEmpty()) { sum += stack.pop(); } return sum; } }