AcWing 3302. 表达式求值
原题链接
简单
作者:
半透明の微笑
,
2024-04-23 22:03:42
,
所有人可见
,
阅读 3
import java.io.*;
import java.util.*;
public class Main{
static Map<Character, Integer> map = new HashMap<>();
static Stack<Integer> num = new Stack<>();
static Stack<Character> op = new Stack<>();
static void eval(){
int num1 = num.pop();
int num2 = num.pop();
char c = op.pop();
int res;
if(c == '+') res = num2 + num1;
else if(c == '-') res = num2 - num1;
else if(c == '*') res = num2 * num1;
else res = num2 / num1;
num.push(res);
}
public static void main(String[] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
map.put('+', 1);
map.put('-', 1);
map.put('*', 2);
map.put('/', 2);
map.put('(', 0);
char[] c = br.readLine().toCharArray();
int len = c.length;
for(int i = 0; i < len; i ++){
if(Character.isDigit(c[i])){
int j = i;
int a = 0;
while(j < len && Character.isDigit(c[j])){
a = a * 10 + (c[j] - '0');
j ++;
}
num.push(a);
i = j - 1;
}else if(c[i] == '('){
op.push(c[i]);
}else if(c[i] == ')'){
while(op.peek() != '(') eval();
op.pop();
}else{
while(op.size() != 0 && map.get(c[i]) <= map.get(op.peek())) eval();
op.push(c[i]);
}
}
while(op.size() != 0) eval();
System.out.println(num.peek());
}
}