The method of variable value Exchange: The third of eclectic programming

Source: Internet
Author: User

The topic is known as two variables A and B, and an algorithm is designed to exchange the values of A and B.

"Method 1" is the most traditional, broadest and most famous method of adding a variable to the code as follows:

int a, b;
int c;
c=a;
a=b;
b=c;

"Method 2" does not add a third variable, swapping the values of A and B, the code is as follows:

int a, b;
a = a+b;
b = a-b;
a=a-b;

Analysis, set A and b the original value of A,b

执行代码   变量a       变量b

int a, b   a         b

a=a+b     a+b         b

b=a-b    a+b        a+b-b=a

a=a-b    a+b-(b)=a+b-a=b   a

"But" this method is only suitable for the integer type and so on, and can not be too large, otherwise there will be overflow.

"Method 3" bitwise operation

执行代码  变量a     变量b

a=a^b;   a^b      b
b=a^b;   a^b      a^b^b=a
a=a^b;   a^b^a=b    a
(异或)

"Ask" we usually use Method 1, Method 2 and Method 3 use less, also know that the following two is less than the 1th way to use a space, but the next two methods used in where?

"Answer": I have not met the use of the place. This is purely a research study that provides a variety of solutions.

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.