C language - given the value of two integer variables, exchange the contents of the two numbers

Given the values ​​of two integer variables, how to swap the contents of the two numbers?

The following is the general practice, the code is as follows:

#include <stdio.h>
intmain()
{
	int a = 4; //You can also enter the value of a, b: int a,b; scanf("%d%d",&a,&b);   
	int b = 1;
	int t = a;
	printf("a=%d\n", b);
	printf("b=%d\n", t);

	return 0;
}

The above method is to store the value of a by creating a temporary variable t, and realize the value exchange of the two variables in an indirect way.

Here are a few common ways to swap the values ​​of two variables without creating a temporary variable:

①Using the addition operation to achieve

code show as below:

#include <stdio.h>
intmain()
{
	int a = 30;
	int b = 20;
	a = a + b;
	b = a - b;
	a = a - b;
	printf("a=%d,b=%d\n", a, b);

	return 0;
}

First let a=a+b, at this time b=ab=(a+b)-b=a, then get a=ab=(a+b)-a=b in the same way. In this way, the value of the two variables is realized exchange.

②Using multiplication to realize

code show as below:

#include <stdio.h>
intmain()
{
        int a = 30;
	int b = 20;
	a = a * b;
	b = a / b;
	a = a / b;
	printf("a=%d,b=%d\n", a, b);

	return 0;
}

This method and the use of addition operations to achieve the same purpose.

First let a=a*b, then b=a/b=(a*b)/b=a, then similarly get a=a/b=(a*b)/a=b. This is achieved Swap the values ​​of two variables.

③Using the bitwise exclusive OR method to realize ※

code show as below:

#include <stdio.h>
intmain()
{
	int a = 30;
	int b = 20;
	a = a^b; //^ is the bitwise XOR operator
	b = a^b;
	a = a^b;
	printf("a=%d,b=%d\n", a, b);

	return 0;
}

The first two methods using addition and multiplication above save time, but overflow occurs when the two numbers involved in the operation are relatively large: Example↓

(For 32-bit and 64-bit compilers, int occupies 32 bits (4 bytes), and the maximum value of int is 2147483647)

The bitwise XOR rule prevents overflow, which reflects the advantage of the bitwise XOR method~

Bitwise XOR method: XOR operation is performed according to binary bits, the same is 0, and the difference is 1 ("same 0 is different from 1").

For example, the original a=30 in the code, its binary code is 0001 1110, b=20, its binary code is 0001 0100, 

After operation:

        a = a^b;
	b = a^b;
	a = a^b;

a=a^b=(0001 1110)^(0001 0100)=(0000 1010)

b=a^b=(0000 1010)^(0001 0100)=(0001 1110)=30

a=a^b=(0000 1010)^(0001 1110)=(0001 0100)=20

In this way, the exchange of the values ​​of the two variables is realized.








Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325818343&siteId=291194637