本题要求你为初学数据结构的小伙伴设计一款简单的利用堆栈执行的计算器。如上图所示,计算器由两个堆栈组成,一个堆栈 S1 存放数字,另一个堆栈 S2 存放运算符。计算器的最下方有一个等号键,每次按下这个键,计算器就执行以下操作:
- 从 S1 中弹出两个数字,顺序为 n1 和 n2;
- 从 S2 中弹出一个运算符 op;
- 执行计算 n2 op n1;
- 将得到的结果压回 S1。
直到两个堆栈都为空时,计算结束,最后的结果将显示在屏幕上。
输入格式:
输入首先在第一行给出正整数 N(1<N≤103),为 S1 中数字的个数。
第二行给出 N 个绝对值不超过 100 的整数;第三行给出 N−1 个运算符 ------ 这里仅考虑 +
、-
、*
、/
这四种运算。一行中的数字和符号都以空格分隔。
输出格式:
将输入的数字和运算符按给定顺序分别压入堆栈 S1 和 S2,将执行计算的最后结果输出。注意所有的计算都只取结果的整数部分。题目保证计算的中间和最后结果的绝对值都不超过 109。
如果执行除法时出现分母为零的非法操作,则在一行中输出:ERROR: X/0
,其中 X
是当时的分子。然后结束程序。
输入样例 1:
5
40 5 8 3 2
/ * - +
输出样例 1:
2
输入样例 2:
5
2 5 8 4 4
* / - +
输出样例 2:
ERROR: 5/0
题目引用自团体程序设计天梯赛真题(2020年)。
java
import java.io.*;
import java.util.Scanner;
import java.util.Stack;
public class Main{
public static void main(String[]args) {
Scanner sc = new Scanner(System.in);
Stack<Integer> s1 = new Stack<>();
Stack<String> s2 = new Stack<>();
int n = Integer.valueOf(sc.nextLine());
String narr[] = sc.nextLine().split(" ");
for (int i = 0; i < narr.length; i++) s1.push(Integer.valueOf(narr[i]));
String ss = sc.nextLine();
String s[] = ss.split(" ");
for (int j = 0; j < n - 1; j++) s2.push(s[j]);
long ans = 0;
int k = n;
int errck = 0;
while (k >= 2) {
k--;
int num1 = s1.pop();
int num2 = s1.pop();
String tmps = s2.pop();
if (tmps.equals("+")) ans = num2 + num1;
if (tmps.equals("-")) ans = num2 - num1;
if (tmps.equals("*")) ans = num2 * num1;
try {
if (tmps.equals("/")) ans = (int) Math.ceil(num2 / num1);
} catch (Exception e) {
System.out.println("ERROR: " + num2 + "/" + num1);
return;
}
s1.push((int) ans);
}
System.out.println(ans);
}
}
class Read {
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
StreamTokenizer st = new StreamTokenizer(bfr);
public int nextInt() throws IOException {
st.nextToken();
return (int) st.nval;
}
public long nextLong() throws IOException {
st.nextToken();
return (long) st.nval;
}
public Double nextDouble() throws IOException {
st.nextToken();
return (Double) st.nval;
}
public String nextLine() throws IOException {
return bfr.readLine();
}
public String next() throws IOException {
return st.sval;
}
}