题解 | #四则运算#
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
System.out.println(calculate(str));
}
public static int calculate(String str) {
// 处理特殊括号,注意替换后的值,不要写错了。且replace后要重新赋值给str
str = str.replaceAll("\\[", "(").replaceAll("\\{", "(").replaceAll("]",
")").replaceAll("}", ")").replaceAll(" ", "");
//初始化两个栈,分别存放运算术和运算符
Stack<Integer> nums = new Stack<>();
Stack<Character> opts = new Stack<>();
char[] cs = str.toCharArray();
int n = cs.length;
boolean flagOpts = false;
boolean isNegativeNumber = false;
for (int i = 0; i < n; i++) {
char c = cs[i];
//判断负数、左括号、右括号、普通运算数、+-*/
if (Character.isDigit(c)) {
int v = c - '0';
int j = i + 1;
while (j < n && Character.isDigit(cs[j])) {
v = v * 10 + cs[j++] - '0';
}
i = j - 1;
if (isNegativeNumber) {
v = -v;
isNegativeNumber = false;
}
nums.add(v);
flagOpts = false ;
} else {
if (flagOpts && c == '-') {
isNegativeNumber = true;
continue;
}
if (c == '(') {
opts.add(c);
} else if (c == ')') {
while (opts.peek() != '(') {
cal(nums, opts);
}
opts.pop();
continue;
} else {
while (!opts.isEmpty() && getPrecedence(c) <= getPrecedence(opts.peek())) {
cal(nums, opts);
}
opts.add(c);
}
flagOpts = true ;
}
}
while (!opts.isEmpty()) {
cal(nums, opts);
}
return nums.peek();
}
// 获取运算符的优先级
public static int getPrecedence(char operator) {
switch (operator) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
}
return 0;
}
public static void cal(Stack<Integer> nums, Stack<Character> opts) {
if (nums.isEmpty() || nums.size() < 2) {
return;
}
if (opts.isEmpty()) {
return;
}
int b = nums.pop(), a = nums.pop();
char op = opts.pop();
int ans = 0;
switch (op) {
case '+' :
ans = a + b;
break;
case '-':
ans = a - b;
break;
case '*':
ans = a * b;
break;
case '/':
ans = a / b;
break;
default:
break;
}
nums.add(ans);
}
}
