XOR Exchange Variable

Source: Internet
Author: User

The usual procedure for exchanging two variables, A/b, is

int temp;

Temp=a

A=b;

B=temp;

the 3rd temporary variable temp above is required .


Using the following method, for a given two integers a, a, the following XOR operation can achieve A/b exchange without the help of the 3rd temporary variable:

A = a ^ b;
b = a ^ b;
A = a ^ b;

This exchange of two variables without the help of the 3rd temporary variable process, the implementation is mainly based on the following properties of the XOR operation:

1. Any one of the variable X and its own XOR operation, the result is 0, that is, x^x=0

2. any one of the variables X and 0 is an XOR operation, the result is unchanged, that is, x^0=x

3. The XOR operation has the binding, namely a^b^c= (a^b) ^c=a^ (b^c)

4. The XOR operation is exchangeable, i.e. A^b=b^a


Analysis:

First step: a = a ^ b;

The result of a variable after completion is a ^ b


Step Two: b = a ^ b;

At this point, a to the right of the assignment number is the value of a ^ B, then the assignment number to the right of a with a ^ B replaced,

Get (a ^ b) ^ B=a ^ (b ^ b) =a ^0=a,

That is, after the second operation, the value in B is a, which is b=a, and a is changed to B.


Step three: a = a ^ b;

At this time the assignment number to the right of a save is still a ^ B value, and the assignment number to the right of B is already a,

Replace the assignment number to the right of the B, respectively,

That is, the assignment number to the right a ^ b= (a ^ b) ^ A=a ^ b^ a=a ^ a^ b=0^ b=b, the value assigned to a, that is a=b

That is, after the third operation, the value in A is B, which is a=b, and B is changed to a.

This completes the exchange of two variables, a, B, as in the three steps above, without the need for a 3rd temporary variable procedure.

This process is equivalent to the following process:

A=a+b

B=a-b;

A=a-b;

The precondition is that the value of the a+b cannot overflow.


XOR Exchange Variable

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.