CCF 二十四點 Java

題目分析:首先想到用棧處理就已經成功一半了。可以定義兩個棧,一個用來存放數字,一個用來存放“+”和“-”,當遇到“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


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章