题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.*; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); s.replace('[', '('); s.replace('{', '('); s.replace('}', ')'); s.replace(']', ')'); System.out.println(solution(s)); } public static int solution(String s) { Deque<Integer> stack = new LinkedList<>(); char ops = '+';//记录运算符号 int num = 0;//记录数字 for (int i = 0; i < s.length(); i++) { if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { while(i < s.length() && s.charAt(i) >= '0' && s.charAt(i) <= '9') { num = num * 10 + s.charAt(i) - '0'; i++; } i--;//for循环还会加1 switch(ops) { case '+' : stack.push(num); break; case '-': stack.push(-num); break; case '*': stack.push(stack.pop() * num);//乘法优先计算 break; case '/': stack.push(stack.pop() / num);//除法优先计算 } num = 0; } else if (s.charAt(i) == '(') { int j = i + 1; int count = 1; while (j < s.length() && count != 0) {//遇到左括号加1,右括号抵消减1 if (s.charAt(j) == '(') count++; if (s.charAt(j) == ')') count--; j++; } num = solution(s.substring(i + 1, j - 1)); i = j - 1; switch(ops) { case '+' : stack.push(num); break; case '-': stack.push(-num); break; case '*': stack.push(stack.pop() * num); break; case '/': stack.push(stack.pop() / num); } num = 0; } else if (s.charAt(i) == '+' || s.charAt(i) == '-' || s.charAt(i) == '*' || s.charAt(i) =='/') { ops = s.charAt(i); } } int res = 0; while (!stack.isEmpty()) { res += stack.pop(); } return res; } }