试题 算法训练 前缀表达式
资源限制
时间限制:1.0s 内存限制:512.0MB
问题描述
编写一个程序,以字符串方式输入一个前缀表达式,然后计算它的值。输入格式为:“运算符 对象1 对象2”,其中,运算符为“+”(加法)、“-”(减法)、“*”(乘法)或“/”(除法),运算对象为不超过10的整数,它们之间用一个空格隔开。要求:对于加、减、乘、除这四种运算,分别设计相应的函数来实现。
输入格式:输入只有一行,即一个前缀表达式字符串。
输出格式:输出相应的计算结果(如果是除法,直接采用c语言的“/”运算符,结果为整数)。
输入输出样例
样例输入
+ 5 2
样例输出
7
Java 代码:
import java.io.*;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] s = in.readLine().split(" ");
int i = 0;
int j = s.length / 2;
int result = 0;
Stack<String> stack = new Stack<>();
// 先计算乘法和除法,将结果存放在栈中,用于下一步进行加减运算
while (j < s.length) {
stack.push(s[j]);
j++;
if (s[i].equals("*")) {
int a = Integer.parseInt(stack.pop());
int b = Integer.parseInt(s[j]);
stack.push(multiply(a, b));
i++;
j++;
} else if (s[i].equals("/")) {
int a = Integer.parseInt(stack.pop());
int b = Integer.parseInt(s[j]);
stack.push(divide(a, b));
i++;
j++;
} else if (s[i].equals("+") || s[i].equals("-")) {
stack.push(s[i]);
i++;
}
}
// 将栈中数据调换顺序
Stack<String> stackTemp = new Stack<>();
while (!stack.empty()) {
stackTemp.push(stack.pop());
}
// 进行加减运算
while (!stackTemp.empty()) {
String c = stackTemp.pop();
if (c.equals("+")) {
result = plus(result, Integer.parseInt(stackTemp.pop()));
} else if (c.equals("-")) {
result = subtract(result, Integer.parseInt(stackTemp.pop()));
} else {
result = Integer.parseInt(c);
}
}
// 输出结果
System.out.println(result);
}
public static int plus(int a, int b) {
return a + b;
}
public static int subtract(int a, int b) {
return a - b;
}
public static String multiply(int a, int b) {
return String.valueOf(a * b);
}
public static String divide(int a, int b) {
return String.valueOf(a / b);
}
}