Three methods for variable value exchange

Source: Internet
Author: User
 

A , B when two variables exchange their values, the most basic practice is to find an intermediate variable for temporary storage, just as there are two water cups, A, B the simplest way to change the water volume of two milliliters of water cups is to find an intermediate cup. C put a cup ( assume that A) the water in is saved in it. Then, set B pour water from the cup to the Cup A . C down to A .

ExchangeA, BFor the values in the two variables, you can find an intermediate variable.CSave:

 
C = A; A = B; B = C;

Although this completes the task, a variable is used. So how can we do this without the third variable? This is a common method:

 
A = a + B; B = A-B; A = A-B;

In this way, the intermediate variable is saved to realize the exchange of two variable values.

Today, I suddenly thought of the third approach:

 
A = a xor B; B = a xor B; A = a xor B;

UseCLanguage:

 
A ^ = B; B ^ = A; A ^ = B;

What is better than the second method above is that there will be no overflow. It is fast, and it is the fastest for anyone to execute bitwise operations on the computer.

Of course, the third method can be used because the XOR operator satisfies the combination and exchange laws. There are also properties a ^ A = 0; a ^ 0 =;

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.