import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class PrefixExpression5 {
// store some constant values
final static long num = 1000000007;
final static long max = Long.MAX_VALUE;
public static void main(String[] args) throws IOException {
// construct a stack to store the calculate values
Stack<Long> st = new Stack<>();
// get the array that stores the input data
String[] elements = readData();
// calculate the result
long result = calculate(elements, st);
// the prefix expression is invalid
if (result == max) {
System.out.println("Invalid");
}
// the prefix expression is valid
else {
// handle the result
result = (result + num) % num;
System.out.println(result);
}
}
public static String[] readData() throws IOException {
// construct a BufferedReader instance
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// real the first line
// split the first line
// read n and k respectively
String line = br.readLine();
int n = Integer.parseInt(line);
//System.out.println(n);
String[] elements = new String[n];
// read the data
for (int i = 0; i < n; i++) {
elements[i] = br.readLine();
}
br.close();
return elements;
}
public static long calculate(String[] arr, Stack<Long> st) {
// store some values that will be used later
String plus = "+";
String minus = "-";
long calRes;
for (int i = arr.length - 1; i >= 0; i--) {
String temp = arr[i];
// if temp is numeric
if (temp.toString().matches("^[0-9]*$")) {
// push the numeric value to the stack
st.push(Long.parseLong(arr[i]) % num);
}
else {
// the expression is not correct
if (st.size() < 2) {
return max;
}
// pop two numbers from the stack and calculate
long a = st.pop();
long b = st.pop();
if (temp.equals(plus)) {
calRes = (a + b) % num;
}
else if (temp.equals(minus)) {
calRes = ((a - b) % num);
}
else {
calRes = ((a * b) % num);
}
// push the result into the stack
st.push(calRes);
}
}
// return the result
return st.pop();
}
}
输入样例
5
*
10
+
20
30
输出
500
oj测试最后一个点超过1s限制没过
求问应如何优化