题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); str = str.replaceAll(" ", ""); System.out.println(cal(str)); } public static int cal(String s) { Stack<Integer> stack = new Stack<>(); int l = s.length(); char[] ch = s.toCharArray(); char sign = '+'; // 数字 int n = 0; for (int i = 0; i < l; i++) { char c = ch[i]; // 拼接字符数字 if (Character.isDigit(c)) { n = n * 10 + c - '0'; } // 如果是括号则统计括号中的数量,进行递归,先计算括号中的值 if (c == '(') { // 从括号的下一位开始计算 int t = i + 1; int count = 1; // 定位一整个括号内的字符,包括括号内的括号 while (count > 0) { // 记录括号的位置 // 右括号,减一,找到对应的左括号 if (ch[t] == ')') count --; // 左括号,有一个则记录一个 if (ch[t] == '(') count++; t++; } // i + 1, t - 1去掉收尾两个括号 n = cal(s.substring(i + 1, t - 1)); i = t - 1; } // 符号计算,乘除则与下一个数计算 if (!Character.isDigit(c) || i == l - 1) { switch (sign) { case '-': stack.push(-1 * n); break; case '*': stack.push(stack.pop() * n); break; case '/' : stack.push(stack.pop() / n); break; case '+': stack.push(n); break; default : ; } // 更新记录数字字符 n = 0; sign = c; } } // 计算栈中的结果 int ans = 0; while(!stack.isEmpty()) { ans += stack.pop(); } return ans; } }