C + + face Test number A, B value interchange (not using intermediate variables) _c language

Source: Internet
Author: User
Tags bitwise

Title Requirement: The value of A and B are exchanged and no intermediate variables are used.

The procedure is as follows:

 #include <stdio.h>

void swapValue1 (int &a, int &b)//Exchanging data with intermediate variables
{
 int temp = A;
 A = b;
 b = temp;
}

void swapValue2 (int &a, int &b)//Use subtraction operation to complete data exchange
{
 A = a + B;
 b = a-b;
 A = A-b; 
}

void SwapValue3 (int &a, int &b)//Using bitwise operations to Exchange data
{
 a^=b;
 B^=a;
 a^=b;
}
int main ()
{
 int a1 = 1, B1 = 2;
 int a2 = 3, b2 = 4;
 int a3 = 5, B3 = 6;
 
 SwapValue1 (A1, B1);
 SwapValue2 (A2, B2);
 SwapValue3 (A3, B3);
 
 printf ("A=%d b=%d\n", A1, B1);
 printf ("A=%d b=%d\n", A2, B2);
 printf ("A=%d b=%d\n", A3, B3);
 
 return 0;
} 

Run Result:

Analytical:
The first: The use of intermediate variables to achieve the purpose of exchanging data, this is the most popular method, of course, do not meet the requirements of the subject.

The second type:
Use simple addition and subtraction operations to achieve the exchange of a, b worthwhile purposes.
Disadvantages:when A+b and A-b, it can lead to data overflow.

The third type:
using the method of bit operation, bitwise XOR OR operation. (Recommended in this way)
XOR: the same bits or operation is 0, the bits XOR is different or the operation is 1.

About the knowledge of bitwise operations, reference http://www.jb51.net/article/87880.htm

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.