An analysis of the principle of using XOR operation to realize two numbers not to exchange values through intermediate variables

Source: Internet
Author: User

Maybe a lot of beginners like me have never seen this symbol ^

This is a different or operational symbol, OK, now we're going to start analyzing how it works!

Knowledge of XOR operation click on this link to learn

Http://baike.baidu.com/view/1452266.htm

After the initial values of I and J are given to 2

respectively for

10--0
5--1
2--0
1

10 binary is 1010

-----------------------------

5--1

2--0

1

5 Binary is 101

The first step:

I=i^j;

Well, we've converted 2 numbers into binary.

Under the different or calculated

1010

0101---complement 0

1111 The result of a---or operation

and convert the binary 1111 to decimal.

1*2^3+1*2^2+1*2^1+1*2^0

8+4+2+1=15

Now the value of I is equal to 15.

Step Two:

J=i^j;

1111

0101

1010

and convert the binary 1010 to decimal.

1*2^3+0*2^2+1*2^1+0*2^0

8+0+2+0=10

Now the value of J is equal to 10.

Step Three:

I=i^j;

1111

1010

0101

Now the value of I is equal to 5.

Finally, the value of I and J is exchanged!

An analysis of the principle of using XOR operation to realize two numbers not to exchange values through intermediate variables

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.