CCF--二十四點


陷阱很多 要細心 ,每一步都要清晰 不然很容易就報錯

  1. 這里的乘號為 x
  2. 一個符號對應一個數字 符號用好之后 還剩一個數字
  3. 四則運算都要用數字進行
  4. debug真是個好東西
import java.util.Scanner;
import java.util.Stack;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		for (int i = 0; i < n; i++) {
			String str = sc.next();
			if (is_24(str))
				System.out.println("Yes");
			else
				System.out.println("No");
		}
	}

	public static boolean is_24(String str) {
		Stack<String> stack = new Stack<String>();
		Stack<Integer> nums = new Stack<Integer>();
		int ans = 0;
		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == '+')
				stack.push(str.charAt(i) + "");
			else if (str.charAt(i) == '-')
				stack.push(str.charAt(i) + "");
			else if (str.charAt(i) == 'x') {
				int flag = str.charAt(i + 1) - '0';
				int temp = nums.pop() * flag ;
				nums.push(temp);
				i++;
			} else if (str.charAt(i) == '/') {
				int flag = str.charAt(i + 1) - '0';
				int temp = nums.pop() / flag;
				nums.push(temp);
				i++;

			} else if (str.charAt(i) - '0' <= 9 && str.charAt(i) - '0' >= 0)
				nums.push(str.charAt(i) - '0');
		}
		while (!stack.isEmpty()) {
			if (stack.peek().equals("-"))
				ans += nums.pop() * (-1);
			else if (stack.peek().equals("+"))
				ans += nums.pop();
			stack.pop();
		}
		ans += nums.pop();
		if (ans == 24)
			return true;
		else
			return false;
	}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM