# 30 lines 7ms fastest Java code very easy to understand

• The idea is simple.

1. choose any 2 numbers A and B and calculate all 6 possible results: A+B, A-B, A*B, A/B, B/A, B-A.
2. choose any result in step 1 and choose one of the two unused numbers as A and B and repeat step 1.
3. choose any result in step 2 as A and the last unused number as B and repeat step 1.
4. if any result in step 3 equals 24 return true otherwise return false.
``````class Solution {
public boolean judgePoint24(int[] nums) {
double[] d=new double[4];
for(int i=0;i<4;i++) d[i]=(double)nums[i];
for(int i=0;i<4;i++){
for(int j=i+1;j<4;j++){
double[] l=new double[2]; int count=0;
for(int k=0;k<4;k++){
if(k!=i&&k!=j) l[count++]=d[k];
}
if(help3(l,d[i]+d[j])||help3(l,d[i]-d[j])||help3(l,d[i]*d[j])
||help3(l,d[i]/d[j])||help3(l,d[j]/d[i])||help3(l,d[j]-d[i]))
return true;
}
}
return false;
}

private boolean help3(double[] l ,double n3) {
double n1=l[0];
double n2=l[1];
return help2(n3 ,n1+n2)||help2(n3 ,n1-n2)||help2(n3 ,n1*n2)||help2(n3 ,n1/n2)||help2(n3 ,n2/n1)||help2(n3 ,n2-n1)
||help2(n2 ,n1+n3)||help2(n2 ,n1-n3)||help2(n2 ,n1*n3)||help2(n2 ,n1/n3)||help2(n2 ,n3/n1)||help2(n2 ,n3-n1)
||help2(n1 ,n3+n2)||help2(n1 ,n3-n2)||help2(n1 ,n3*n2)||help2(n1 ,n3/n2)||help2(n1 ,n2/n3)||help2(n1 ,n2-n3);
}

private boolean help2(double n1, double n2) {
return near24(n1+n2)||near24(n1-n2)||near24(n1*n2)||near24(n1/n2)||near24(n2/n1)||near24(n2-n1);
}

private boolean near24(double d){
return (d<24.001)&&(d>24-0.001);
}
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.