题解 | #表达式求值#
表达式求值
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); // 注意 hasNext 和 hasNextLine 的区别 // while (in.hasNextInt()) { // 注意 while 处理多个 case // int a = in.nextInt(); // int b = in.nextInt(); // System.out.println(a + b); // } String line = in.nextLine(); System.out.print(solve(line)); } private static int solve(String s) { int len = s.length(); char[] cs = s.toCharArray(); Stack<Integer> stack = new Stack<>(); int number = 0; char sign = '+'; for (int i = 0; i < len; i++) { char c = cs[i]; if (c == ' ') { continue; } if (Character.isDigit(c)) { number = number * 10 + (c - '0'); } if (c == '(') { int j = i + 1; int count = 1; while (count > 0) { if (cs[j] == '(') { count++; } if (cs[j] == ')') { count--; } j++; } number = solve(s.substring(i + 1, j - 1)); i = j - 1; //指向数字 } if (!Character.isDigit(c) || i == len - 1) { if (sign == '+') { stack.push(number); } if (sign == '-') { stack.push(-1 * number); } if (sign == '*') { stack.push(stack.pop() * number); } if (sign == '/') { stack.push(stack.pop() / number); } sign = c; number = 0; } } int result = 0; while (!stack.isEmpty()) { result += stack.pop(); } return result; } }