Three methods of variable value Exchange

Source: Internet
Author: User
"title"Two variables A and b are known, and an algorithm is designed to exchange values of a and B. "Method 1" is the most traditional, broadest, and most famous method, adding a variable to the code as follows: int A, B; int C; c = A; A = b; b = C; "Method 2" Without adding a third variable, swap the values of A and B with the following code: int A, A; A = A+b; B = A-B; A = a-B;   Analysis, set the original value of a and B to execute code                      variable a        variable 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 integral type and so on, and can not be too large, otherwise there will be overflow. "Method 3"Bit operations execute code variable a variable b a=a^b; A^b b
B=a^b; A^b A^b^b=a
A=a^b; A^b^a=b A
(XOR)

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.