Three ways to exchange two numbers

Source: Internet
Author: User

Remember when I first started to learn C + +, also did two number of exchanges, then only used the following first and the third method, today in the Reading of Wisdom Podcast Java Video tutorial, learned another two ways

Suppose a=10,b=20, swap the value of a A, b

Method one, using third-party variables, is also the most common method

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

Method Two, bitwise XOR OR operation

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

Method Three, add the variables


Method Four, a sentence to be done

b= (a+b)-(A=B);

The first method that is commonly used in the actual work

Three ways to exchange two numbers

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: 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.