Java Judge 4 of the number within 10, through arithmetic to get 24

Source: Internet
Author: User
Tags arithmetic

Please use Java to write a method to determine the given 4 digits, each value between 1~10, through +-*/operation, the result is 24, each number must be used and can only be used once.

The exhaustive method provided by netizens

public class T {


int[] can = new int[4];


public static void Main (string[] args) {


t tf = new T (3, 4, 5, 7);


System.out.println (Tf.getresult ());


 }


public T (int a, int b, int c, int d) {


can[0] = A;


can[1] = b;


can[2] = c;


can[3] = D;


 }


public String GetResult () {


double result1 = 0;


double result2 = 0;


double result3 = 0;


for (int i = 0; i < 4; i++) {


for (int j = 0; J < 4; + +) {


for (int k = 0; k < 4; k++) {


if (i!= j) {


result1 = Cal (Can[i], can[j], k);


for (int l = 0; l < 4; l++) {


for (int m = 0; m < 4; m++) {


if (i!= l && J!= L) {


result2 = Cal (Result1, Can[l], M);


for (int n = 0; n < 4; n++) {


for (int o = 0; o < 4; o++) {


if (i!= n && j!= n && l!= N) {


RESULT3 = Cal (Result2, can[n), O);


if (RESULT3 = = 24) {


return result (Can[i], K, Can[j], M, Can[l], O, can[n]);


            }


           }


          }


         }


        }


       }


      }


     }


    }


   }


  }


return null;


 }


private String result (int can1, int op1, int can2, int op2, int can3, int op3, int can4) {


Return "" + Can1 + CONVERT (OP1) + can2 + CONVERT (OP2) + can3 + CONVERT (OP3) + Can4;


 }


private String convert (int opr) {


if (OPR = = 0) {


return "+";


} else if (OPR = 1) {


return "-";


} else if (OPR = 2) {


return "*";


} else if (OPR = 3) {


return "/";


  }


return "";


 }


private Double cal (double A, double b, int opr) {


if (OPR = = 0) {


return a + B;


} else if (OPR = 1) {


return a-b;


} else if (OPR = 2) {


return a * b;


} else if (OPR = 3) {


return a/b;


  }


return 0;


 }


}

Operation result

3*4+5+7

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.