1. 思路分析
7*2*2-5+1-5+3-4 = ?
- 通过一个 index 值(索引),来遍历我们的表达式
- 如果我们发现是一个数字, 就直接入数栈
- 如果发现扫描到是一个符号, 就分如下情况
3.1 如果发现当前的符号栈为空,就直接入栈
3.2 如果符号栈有操作符,就进行比较,如果当前的操作符的优先级小于或者等于栈中的操作符, 就需要从数栈中pop出两个数,在从符号栈中pop出一个符号,进行运算,将得到结果,入数栈,然后将当前的操作符入符号栈, 如果当前的操作符的优先级大于栈中的操作符, 就直接入符号栈 - 当表达式扫描完毕,就顺序的从数栈和符号栈中pop出相应的数和符号,并运行.
- 最后在数栈只有一个数字,就是表达式的计算结果
2. 代码实现
public class Calculator {
public static void main(String[] args) {
String expression = "7*2*2-5+1-5+3-4";
ArrayStack numStack = new ArrayStack(10);
ArrayStack operStack = new ArrayStack(10);
int index = 0;
int num1 = 0;
int num2 = 0;
int oper = 0;
int res = 0;
char ch = ' ';
String keepNum = "";
while (true) {
ch = expression.substring(index, index + 1).charAt(0);
if (isOper(ch)) {
if (!operStack.isEmpty()) {
if (priority(ch) <= priority(operStack.peek())) {
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = cal(num1, num2, oper);
numStack.push(res);
operStack.push(ch);
}else {
operStack.push(ch);
}
}else {
operStack.push(ch);
}
}else {
keepNum += ch;
if (index == expression.length() - 1) {
numStack.push(Integer.parseInt(keepNum));
}else {
if (isOper(expression.substring(index + 1, index + 2).charAt(0))) {
numStack.push(Integer.parseInt(keepNum));
keepNum = "";
}
}
}
index++;
if (index >= expression.length()) {
break;
}
}
while (true) {
if (operStack.isEmpty()) {
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = cal(num1, num2, oper);
numStack.push(res);
}
int result = numStack.pop();
System.out.printf("表达式 %s = %d", expression, result);
}
public static int priority(int oper) {
if (oper == '*' || oper == '/') {
return 1;
} else if (oper == '+' || oper == '-') {
return 0;
}else {
return -1;
}
}
public static boolean isOper(char val) {
return val == '+' || val == '-' || val == '*' || val == '/';
}
public static int cal(int num1, int num2, int oper) {
int res = 0;
if (oper == '+') {
res = num1 + num2;
} else if (oper == '-') {
res = num2 - num1;
} else if (oper == '*') {
res = num1 * num2;
} else if (oper == '/') {
res = num2 / num1;
}
return res;
}
}
class ArrayStack {
private int maxSize;
private int[] stack;
private int top = -1;
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
public int peek() {
return stack[top];
}
public boolean isFull() {
return top == maxSize - 1;
}
public boolean isEmpty() {
return top == -1;
}
public void push(int value) {
if (isFull()) {
System.out.println("栈满");
return;
}
top++;
stack[top] = value;
}
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈空");
}
int value = stack[top];
top--;
return value;
}
public void list() {
if (isEmpty()) {
System.out.println("栈空");
return;
}
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
}
表达式 7*2*2-5+1-5+3-4 = 18