package 数据结构;
import java.util.Stack;
public class StackDemo {
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println(calculator.calculate("700+2*6-4"));
}
}
class Calculator{
Stack numStack = new Stack<>();
Stack operaStack = new Stack<>();
int calculateByTwo(int num1, int num2, char opera){
int res = 0;
if (opera == '+') res = num1 + num2;
if (opera == '-') res = num2 - num1;
if (opera == '*') res = num1 * num2;
if (opera == '/') res = num2 / num1;
return res;
}
int calculate(String str){
int res = 0;
int num1, num2;
char opera;
int index = 0;
String keepNum = "";
do {
char ch = str.charAt(index);
if (Character.isDigit(ch)) {
keepNum = keepNum + ch;
if (index+1 == str.length()){
numStack.push(Integer.parseInt(keepNum));
}else if (isOpera(str.charAt(index+1))){
numStack.push(Integer.parseInt(keepNum));
keepNum = "";
}
}
if (isOpera(ch)) {
if (operaStack.isEmpty()) {
operaStack.push(ch);
} else {
if (priority(ch) <= priority(operaStack.peek())) {
num1 = numStack.pop();
num2 = numStack.pop();
opera = operaStack.pop();
numStack.push(calculateByTwo(num1, num2, opera));
operaStack.push(ch);
} else {
operaStack.push(ch);
}
}
}
index++;
} while (index < str.length());
while (!operaStack.isEmpty()) {
//如果符号栈为空,代表数栈只剩一个数,即计算结果
num1 = numStack.pop();
num2 = numStack.pop();
opera = operaStack.pop();
numStack.push(calculateByTwo(num1, num2, opera));
}
res = numStack.pop();
return res;
}
//判断是否操作符
boolean isOpera(char c){
return c == '+' || c == '-' || c == '*' || c == '/';
}
//判断优先级
int priority(char c){
return switch (c) {
case '+', '-' -> 1;
case '*', '/' -> 2;
default -> -1;
};
}
}