Home » Java » 24

24

 given 4 positive integers less than 10, you can use 4 kinds of operations, including add, subtract, multiply and divide
The problem is to connect the 4 numbers to get an expression. The question now is whether there is a way that the result of the expression is equal to 24.
Here, the calculation results and the brackets add, subtract, multiply and divide operations with our usual priority
The definition is consistent (the division here is defined as real division)
For example, for 5,5,5,1, we know 5 * (5 - 1 / 5) = 24 due to
This can get 24., and for example, for 1,1,4,2, we can't get it
24.
input
The input data consists of multiple lines, each line giving a set of test data, including 4 less than 10 positive integers
The last set of test data consists of 4 0, which represents the end of the input, which is not processed
output
For each set of test data, a line is output, and if you can get 24, output "YES"";
Otherwise, output "NO"
sample input
5551
1142
0000
sample output
YES
NO

problem solving thinking:

N number 24, there will be two numbers to count. The two count results, and the remaining number of n-2, is the N-1 number for 24. Two the number of enumeration count, and the number of operations of these two.N is 1, if the output is equal to 24 true,
and false. output
Note: floating-point comparison is equal, not to be less than 10^-6. The government can be regarded as equal to 24 and.


The

code is as follows:


import java.util.Scanner;
Public, class, Main {
Public, static, Boolean, IsZero (double, a) {
Return Math.abs (a) < = 0.000001;
}
Public, static, Boolean, count24 (double[], num, int, n) {
If (n = = 1) {
If (IsZero (num[0]-24)) {
Return true;
}else{
Return false;
}
}
Double[] a = new double[5];
For (int i = 0; I < n-1; i++) {
For (int j = i+1; J < n; j++) {
Int m = 0;
For (int k = 0; K < n; k++) {
If (k! = I & & K! = J) {
A[m++] = num[k];
}
}
A[m] = num[i] + num[j];
If (count24 (a, m+1)) {
Return true;
}
A[m] = num[i] - num[j];
If (count24 (a, m+1)) {
Return true;
}
A[m] = num[j] - num[i];
If (count24 (a, m+1)) {
Return true;
}
A[m] = num[i] * num[j];
If (count24 (a, m+1)) {
Return true;
}
If ((IsZero (num[j])) {
A[m] = num[i] / num[j];
If (count24 (a, m+1)) {
Return true;
}
}
If ((IsZero (num[i])) {
A[m] = num[j] / num[i];
If (count24 (a, m+1)) {
Return true;
}
}
}
}
Return false;
}
Public, static, void, main (String[], args) {
Auto-generated method stub / / TODO
Scanner in = new Scanner (System.in);
Double[] num = new double[5];
While (true) {
For (int, I = 0, I, < 4, i++) {
Num[i] = in.nextDouble ();
}
If (num[0] = = 0) {
Break;
}
If (count24 (Num, 4)) {
System.out.println ("Yes");
}else{
System.out.println ("No");
}
}
In.close ();
}
}

Latest