题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
static Deque<Integer> num = new ArrayDeque<>();
static Deque<Character> op = new ArrayDeque<>();
static Map<Character, Integer> pr = new HashMap<>();
public static boolean digit(char c) {
return c >= '0' && c <= '9';
}
public static void compute() {
int b = num.pop(); // 第一个出栈的是第二个操作数
int a = num.pop();
char c = op.pop();
int x = 0;
if (c == '+') x = a + b;
else if (c == '-') x = a - b;
else if (c == '*') x = a * b;
else x = a / b;
num.push(x);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String exp = sc.nextLine();
pr.put('+', 1);
pr.put('-', 1);
pr.put('*', 2);
pr.put('/', 2);
char lastch = ' ';
char symbol = '+';
for (int i = 0; i < exp.length(); i ++) {
char c = exp.charAt(i);
if (digit(c)) {
int x = 0, j = i;
while (j < exp.length() && digit(exp.charAt(j)))
x = x * 10 + exp.charAt(j ++) - '0';
i = j - 1;
if (symbol == '-') x = x * (-1);
num.push(x);
}
else if (c == '(') op.push(c);
else if (c == ')') {
while(op.peek() != '(') compute();
op.pop();
}
else {
if (c == '-' && !digit(lastch) && lastch != ')') symbol = '-';
else {
symbol = '+';
while (op.size() != 0 && op.peek() != '(' &&
pr.get(op.peek()) >= pr.get(c)) compute();
op.push(c);
}
}
lastch = c;
}
while(op.size() != 0) compute();
System.out.println(num.peek());
}
}
美的集团公司福利 798人发布