Java implements two int number exchanges

Source: Internet
Author: User

Common method, advanced method, great God method

1 @Test2      Public voidtest3 () {3         intm = 5;4         intn = 12;5         6         //requires M and N swap locations7System.out.println ("m=" + M + "n=" + N);//m=5 n=128         9         //method One: Define temporary variablesTen         //Advantages: Simple operation, disadvantage: need to define temporary variables, memory consumption is large One         inttemp =m; Am =N; -n =temp; -System.out.println ("m=" + M + "n=" + N);//m=12 n=5 the          -         //method Two: Do not define temporary variables, use Add -         //Pros: Save memory by not having to define temporary variables. Cons: Easy to lose accuracy when two values are large -m = m + N;//5 + +n = m-n;//12 + 5-5, is the value of the original m, assigned to n -m = m-n;//12 + 5-12, is the value of the original N, assigned to M +System.out.println ("m=" + M + "n=" + N);//m=5 n=12 A          at         //Method Three: Dedicated to the gods, using XOR or ^ -         //Advantages: No loss of precision, no definition of variables, memory consumption is minimal, disadvantage: ordinary people will not think so write, write the General people also can not understand -m = m ^N; -n = m ^ n;//m ^ n ^ n = = M -m = m ^ n;//m ^ n ^ m = = N -System.out.println ("m=" + M + "n=" + N);//m=12 n=5 in          -}

Method Two is not recommended because it is possible to lose precision

Java implements two int number exchanges

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.