描述
输入一个表达式(用字符串表示),求这个表达式的值。
保证字符串中的有效字符包括[‘0’-‘9’],‘+’,‘-’, ‘*’,‘/’ ,‘(’, ‘)’,‘[’, ‘]’,‘{’ ,‘}’。且表达式一定合法。
数据范围:表达式计算结果和过程中满足 ∣val∣≤1000 ,字符串长度满足 1≤n≤1000
输入描述:
输入一个算术表达式
输出描述:
得到计算结果
示例1
输入:
3+2*{1+2*[-4/(8-6)+7]}
输出:
25
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String expression = scanner.nextLine();
int result = calculate(expression);
System.out.println(result);
}
public static int calculate(String expression) {
Stack<Integer> operands = new Stack<>();
Stack<Character> operators = new Stack<>();
int i = 0;
while (i< expression.length()) {
char c = expression.charAt(i);
if (c == ' ') {
i++;
continue;
}
if (Character.isDigit(c)) {
int j = i;
while (j< expression.length() && Character.isDigit(expression.charAt(j))) {
j++;
}
int value = Integer.parseInt(expression.substring(i, j));
operands.push(value);
i = j;
} else if (c == '(') {
operators.push(c);
i++;
} else if (c == ')') {
while (operators.peek() != '(') {
int b = operands.pop();
int a = operands.pop();
char op = operators.pop();
int result = applyOperator(a, b, op);
operands.push(result);
}
operators.pop();
i++;
} else if (isOperator(c)) {
while (!operators.isEmpty() && operators.peek() != '(' && compare(c, operators.peek()) <= 0) {
int b = operands.pop();
int a = operands.pop();
char op = operators.pop();
int result = applyOperator(a, b, op);
operands.push(result);
}
operators.push(c);
i++;
} else {
i++;
}
}
while (!operators.isEmpty()) {
int b = operands.pop();
int a = operands.pop();
char op = operators.pop();
int result = applyOperator(a, b, op);
operands.push(result);
}
return operands.pop();
}
public static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
public static int compare(char op1, char op2) {
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) {
return 1;
}
return 0;
}
public static int applyOperator(int a, int b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
return 0;
}
}
}
这个程序首先从输入中读取算术表达式,然后使用 calculate
函数来计算表达式的值。calculate
函数使用两个栈来存储操作数和操作符,并使用一个 i
变量来遍历表达式中的字符。在遍历过程中,程序会根据字符的类型来执行相应的操作,例如将数字压入操作数栈、将操作符压入操作符栈、计算表达式的值等。最后,程序返回计算结果。
isOperator
函数用于判断一个字符是否是操作符,compare
函数用于比较两个操作符的优先级,applyOperator
函数用于计算两个操作数之间的运算结果。
注意,这个程序使用了 Stack
类来实现栈,并使用了 Scanner
类来读取输入。在 calculate
函数中,我们使用了两个栈来存储操作数和操作符,并使用一个 i
变量来遍历表达式中的字符。在遍历过程中,程序会根据字符的类型来执行相应的操作,例如将数字压入操作数栈、将操作符压入操作符栈、计算表达式的值等。最后,程序返回计算结果。