The 16th CCF CSP certification "24 points" python java

Keywords: Java Python

python and java each give a solution.

 

python's eval() function has a natural advantage in solving this problem. The main need to pay attention to the use of double slashes for division, and retain integer.

a=input();
for i in range(int(a)):
    b=input().replace("x", "*").replace("/", "//");
    if(eval(b)==24):
        print("Yes")
    else:
        print("No")

 

java

Use ArrayList < string > to save numbers and symbols.

The first step is to find out the operation position: if the list has multiplication and division operation, the operation position is at the first multiplication sign / division sign. If the list has no multiplication and division operation, the operation position is at the first symbol. Step 2, local operation: according to the subscript of the operator found in step 1, calculate the answer, and then replace the original operation triplet with the answer. At this point, the size of the list is reduced by 2

Then, repeat the first and second steps until the calculation is completed.

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		int n=in.nextInt();
		in.nextLine();
		while(n-->0){
			String s=in.nextLine();
			ArrayList<String>list=new ArrayList<>(); 
			for(int i=0;i<7;i++){
				list.add(s.substring(i,i+1));
			}
			if(f(list)==24)
				System.out.println("Yes");
			else
				System.out.println("No");
		}
	}
	public static int f(ArrayList<String>list){//Recursive computation
		if(list.size()==3)//Recursive export
			return f2(list.get(0),list.get(1),list.get(2));
		for(int i=0;i<list.size();i++){
			if(list.get(i).equals("x")||list.get(i).equals("/")){
				list.set(i,""+f2(list.get(i-1),list.get(i),list.get(i+1)));
				list.remove(i+1);
				list.remove(i-1);
				return f(list);
			}
		}
		list.set(1,""+f2(list.get(0),list.get(1),list.get(2)));
		list.remove(2);
		list.remove(0);
		return f(list);
	}
	public static int f2(String x1,String x2,String x3){//Calculate a short formula
		int a=Integer.parseInt(x1);
		int b=Integer.parseInt(x3);
		if(x2.equals("+"))
			return a+b;
		else if(x2.equals("-"))
			return a-b;
		else if(x2.equals("x"))
			return a*b;
		else return a/b;
	}
}

 

Posted by StormS on Thu, 05 Dec 2019 00:48:49 -0800