AcWing 454. 表达式求值——Java代码版
原题链接
中等
作者:
三玖天下第一
,
2021-03-26 15:59:31
,
所有人可见
,
阅读 285
import java.io.*;
import java.util.ArrayDeque;
public class Main{
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
ArrayDeque<Integer> nums = new ArrayDeque<>();
ArrayDeque<Character> ops = new ArrayDeque<>();
char[] temp = reader.readLine().toCharArray();
for (int i = 0; i < temp.length; i++) {
char c = temp[i];
//当是数字时,计算数字的值
if (c >= '0' && c <= '9'){
int j = i+1, value = Integer.parseInt(String.valueOf(c));
while(j < temp.length && temp[j] >= '0' && temp[j] <= '9'){
value = (value*10 + Integer.parseInt(String.valueOf(temp[j])))% 10000;
j++;
}
nums.push(value);
i = j-1;
//当是加号时,只要操作符栈非空,就一直计算
}else if (c == '+'){
while(!ops.isEmpty()){
char d = ops.pop();
if (d == '+'){
nums.push((nums.pop() + nums.pop())% 10000);
}else{
nums.push((nums.pop() * nums.pop())% 10000);
}
}
ops.push(c);
//当是乘号时,仅当操作符栈非空且为乘号时才进行计算
}else{
while(!ops.isEmpty() && ops.peek() == '*'){
nums.push((nums.pop() * nums.pop())% 10000);
ops.pop();
}
ops.push(c);
}
}
//当操作符栈非空时,按顺序计算数值即可,只会存在最多一个乘号
while(!ops.isEmpty()){
char x = ops.pop();
if (x == '+'){
nums.push((nums.pop() + nums.pop())% 10000);
}else{
nums.push((nums.pop() * nums.pop())% 10000);
}
}
System.out.println(nums.pop() % 10000);
}
}
啊这
orz