某大神的,理解后敲出来。题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.Scanner; import java.util.Stack; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); scanner.useDelimiter("\n"); while (scanner.hasNext()) { String S = scanner.next(); S = S.replaceAll("\\[", "(").replaceAll("]", ")") .replaceAll("\\{", "(").replaceAll("}", ")"); System.out.println(yunsuan(S)); } } public static int yunsuan(String S) { char opt = '+'; int length = S.length(); Stack<Integer> stack = new Stack<>(); for (int i = 0; i < S.length(); i++) { char c = S.charAt(i); if (Character.isDigit(c)) { int num = 0; while (i < length && Character.isDigit(S.charAt(i))) { num = num * 10 + S.charAt(i) - 48; i++; } i--; if (opt == '+') stack.push(num); else if (opt == '-') stack.push(-num); else if (opt == '*') stack.push(stack.pop() * num); else if (opt == '/') stack.push(stack.pop() / num); } else if (c == '+' || c == '-' || c == '*' || c == '/') { opt = c; } else if (c == '(') { int left = i; int right = i + 1; int count = 1; while (right < length && count > 0) { if (S.charAt(right) == '(') count++; if (S.charAt(right) == ')') count--; right++; } i = right - 1; int num = yunsuan(S.substring(left + 1, right - 1)); if (opt == '+') stack.push(num); else if (opt == '-') stack.push(-num); else if (opt == '*') stack.push(stack.pop() * num); else if (opt == '/') stack.push(stack.pop() / num); } } int res = 0; while (!stack.isEmpty()) { res += stack.pop(); } return res; } }