Two integers are exchanged without the third variable.

Source: Internet
Author: User

Assume that there are two numbers X and Y:

Method 1: arithmetic operation (addition or subtraction ):

X = x + y; // y = x-y for temporary storage. // y is the sum of the two numbers Minus Y, that is, the original xx = x-y; // X is the sum of the two numbers minus the current y (the original X) to change to the original y

Method 2: logical operation (exclusive or ):

X ^ = y; // Save the information of X and Y first. y ^ = x; // keep X unchanged, use X to exclusive or reverse the original value of Y to make it equal to the original value of x ^ = y; // keep Y unchanged, use X to exclusive or reverse the original value of Y to make it equal to the original value of Y.

Two principles should be kept in mind for exclusive or operations:

Any binary number with the same 1 variance or will change to another (0 with the same 1 variance or the result is with the same 1 variance or the result is 0)
The binary number of any digit is the same as 0 or both remain unchanged (0 is the same as 0 or 0 is the same as 0, and the result is 1)

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.