题目
给定一个表达式,其中运算符仅包含 +,-,*,/(加 减 乘 整除),可能包含括号,请你求出表达式的最终值
输入
(2+2)*(1+1)
输出
8
public class 中缀表达式求值 {
//初始化
public static HashMap<Character, Integer> priority = new HashMap<>();
public static Stack<Character> op = new Stack<>();
public static Stack<Integer> num = new Stack<>();
public static void main(String[] args) {
//初始化
Scanner in = new Scanner(System.in);
String str = in.nextLine();
priority.put('+', 1);
priority.put('-', 1);
priority.put('*', 2);
priority.put('/', 2);
for (int i = 0; i<str.length(); i++) {
char c_now = str.charAt(i);
//数字处理,进行判断,以防出现多位数字
if (Character.isDigit(c_now)){
int x = 0, j = i;
while (j < str.length() && Character.isDigit(str.charAt(j))){
x = x * 10 + str.charAt(j) - '0'; //这一句是把char的数加起来用的,不理解也可以用,不影响
j++;
}
num.push(x);
i = j - 1;
}
//括号的处理
else if (c_now == '(') {op.push(c_now);}
else if (c_now == ')') {
while (op.peek() != '('){calc();}
op.pop();
}
//运算符的处理,同时判断优先级
else {
while (!op.isEmpty() && op.peek() != '(' && priority.get(op.peek()) >= priority.get(c_now)) {calc();}
op.push(c_now);
}
}
//对剩余的数字和运算符进行处理
while (!op.isEmpty()) {calc();}
System.out.println(num.peek());
}
//进行计算,切记先拿的是b,后拿的是a,否则减法可能有问题
public static void calc() {
int b = num.pop(), a = num.pop();
char op_now = op.pop();
if (op_now == '+'){num.push(a + b);}
else if (op_now == '-') {num.push(a - b);}
else if (op_now == '*') {num.push(a * b);}
else if (op_now == '/') {num.push(a / b);}
}
}
中缀表达式网上应该有很多解释了把,我就不多讲了,添加其他的符号啥的也很简单,基本思路都差不多
声明:算法思路来源为y总,详细请见https://www.acwing.com/
本文仅用作学习记录和交流