题目分析:首先想到用栈处理就已经成功一半了。可以定义两个栈,一个用来存放数字,一个用来存放“+”和“-”,当遇到“x”和“/”时,取出数字栈中栈顶元素与读取下一个数字进行 乘 or 除 操作,并将所得数字存到数字栈,其他的存放到符号栈。然后再定义两个栈,对以上两个栈元素进行颠倒,考虑(7-9-1-2)的情况。接下来直接进行操作就可以了。
以上方法过于麻烦,开辟过空间。只开辟一个栈空间。遇到乘和除的操作同上,遇到减,往栈中添加下一个读取数字的负数即可。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Stack;
public class Main{
public static void main(String[] args) throws IOException {
BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));
String []line = bReader.readLine().split(" ");
int n = Integer.parseInt(line[0]);
ArrayList<String>list = new ArrayList<String>();
for(int i=0;i<n;i++) {
String string = bReader.readLine();
Stack<Integer>stack1 = new Stack<Integer>();
Stack<String>stack2 = new Stack<String>();
for(int j=0;j<7;++j) {
if(j%2==0)
stack1.add(Integer.parseInt(string.charAt(j)+""));
else {
if(string.charAt(j)=='x') {
int num1 = stack1.pop();
int num2 = Integer.parseInt(string.charAt(j+1)+"");
++j;
stack1.add(num1*num2);
}
else if(string.charAt(j)=='/') {
int num1 = stack1.pop();
int num2 = Integer.parseInt(string.charAt(j+1)+"");
++j;
stack1.add(num1/num2);
}
else {
stack2.add(string.charAt(j)+"");
}
}
}
Stack<Integer>stack3 = new Stack<Integer>();
Stack<String>stack4 = new Stack<String>();
while(!stack1.isEmpty())
stack3.add(stack1.pop());
while(!stack2.isEmpty())
stack4.add(stack2.pop());
while((!stack3.isEmpty())&&(!stack4.isEmpty())) {
int num1 = stack3.pop();
int num2 = stack3.pop();
String s = stack4.pop();
if(s.equals("-"))
num1 -= num2;
else
num1 += num2;
stack3.add(num1);
}
if((stack3.pop())==24)
list.add("Yes");
else
list.add("No");
}
for (String str : list) {
System.out.println(str);
}
}
}
//10
//9+3+4x3
//5+4x5x5
//7-9-9+8
//5x6/5x4
//3+5+7+9
//1x1+9-9
//1x9-5/9
//8/5+6x9
//6x7-3x6
//6x4+4/5