Two variable Exchange four methods (Java) seven Methods (JS)

Source: Internet
Author: User

For the exchange of two variables, I found four methods, below I use Java to illustrate.

1. Use the third variable to exchange values, a simple method.

(Code Demo)

1 class Testev 2//Create a Class 3 {4 public     static void Main (String[]args) 5     {6         int x =5,y=10;//define two variables 7         8
   int temp = x;        Define the third Temp variable temp and extract the X value 9         x = y;      Assign the value of Y to x10         y = temp; The temporary variable temp value is then assigned to         Y11         System.out.println ("x=" +x+ "y=" +y);     }15     16}17         

2. It is possible to exchange data in the same way that two numbers are summed and subtracted, and the disadvantage is that if the values of x and Y are too large, the value exceeding int will lose precision.

(Code Demo)

1 class Testev 2//Create a Class 3 {4 public     static void Main (String[]args) 5     {6         int x =5,y=10;//define two variables 7          8
   
    x = x + y;        X () = 5 + 9         y = x-y;        Y (5) = x (All)-ten;        Ten         x = XY;        X (Ten) = X (All)-Y (5)         System.out.println ("x=" +x+ "y=" +y);     }14     15}             
   

3. The use of bitwise operation of the data exchange, the use of the idea is: a number of different or the same number two times, the result is that number, and will not exceed the int range

(Code Demo)

1 class Testev 2//Create a Class 3 {4 public     static void Main (String[]args) 5     {6         int x =5,y=10;//define two variables 7          8
   
    x = X^y; 9         y = x^y;  Y= (x^y) ^y10         x = x^y;  x= (x^y) ^x11         System.out.println ("x=" +x+ "y=" +y);     }14     15}                   
   

  

4. Simplest, swap variables directly at the time of printout

(Code Demo)

1 class Testev 2//Create a Class 3 {4 public     static void Main (String[]args) 5     {6         int x =5,y=10;//define two variables 7          8         System.out.println ("x=" +y+ "y=" +x);//Exchange 9     }11     12} directly at the time of output      

Objective

This article summarizes seven ways to exchange values for variables A and b

?
12 vara = 123;varb = 456;

Exchange Variable Value scheme one

The simplest way to do this is to use a temporary variable, but the method of using temporary variables is too low.

?
1234 vart;t = a;a = b;b = t;

First, the value of a is stored in a temporary variable, then B is assigned to a, and finally the value of a in the temporary variable assigned to B, this method is the most basic

Exchange Variable Value Scheme II

The following scenarios do not have temporary variables, I summed up, in fact, the idea of not using temporary variables is to let one of the variables into a and B are related to the value, so you can change the value of another variable, and finally change the original modified variable value

Like this one.

?
123 a += b;b = a - b;a -= b;

Let a first become a and B's ' and ' (can also be changed to A and B, the same), ' and ' minus B cleverly obtained a variable value assigned to B, and then by ' and ' minus A is worth the value of B given a, or the following variant (the form of difference)

?
123 a -= b;b = a + b;a = b - a;

But feelings and forms are easier to understand.

Exchange Variable Value Scheme III

This method for the first time to learn JavaScript may not understand, because our JavaScript is rarely used in place, this is what I learned before the algorithm contest book, through the underlying bit operation to exchange variable values, is the above scheme evolved

?
123 a ^= b;b ^= a;a ^= b;

Know that C + + can even a^=b^=a^=b do the job, but I find that JavaScript can't

But we can do this.

?
1 a = (b^=a^=b)^a;

Exchange Variable Value Scheme four

Turn A into an object, this object holds the key value pairs that should be exchanged, and the last assignment is done.

?
123 a = {a:b,b:a};b = a.b;a = a.a;

Exchange Variable Value Scheme five

Much like the method above, except that the object was replaced with an array

?
123 a = [a,b];b = a[0];a = a[1];

Exchange Variable Value Scheme VI

This method is very ingenious, not I thought out, the person who thinks out must be the great God, unless he is a dream come out, simple rude line of code exchanged a and B variable values

?
1 a = [b,b=a][0];

According to the operator precedence, the first execution b=a , at this time B directly get a variable value, and then a step array index let a get the value of B (can not be more powerful)

Exchange Variable Value Scheme VII

Finally, my solution is to take advantage of ES6 's deconstructed assignment syntax, which allows us to extract the values of arrays and objects, and assign values to variables, but I now have a test Chrome browser that has implemented

?
1 [a,b] = [b,a];

You can see that the deconstruction assignment syntax makes our exchange variable values super-simple, and this deconstructed assignment syntax is a lot more than the focus of the day, and will not be talked about in the future.

Summarize

This article refers to so many methods of exchanging variable values, I do not know if there is any other way, although it is an insignificant problem, but can practice our brain hole. Hope that the content of this article on everyone's study or work can bring certain help, if there is doubt you can message exchange.

Two variable Exchange four methods (Java) seven Methods (JS)

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.