Several methods of exchanging integer variable content

Several ways to exchange plastic content, look at this Code
1. Create a temporary variable exchange shaping content. To swap two plastic content by means of creating a temporary variable, with special attention: Inside the function you want to change the content of external variables of the function parameters need to transfer addresses, known as pass-by-call;

void Change(int* pa, int* pb)
{
 int tmp = *pa;
 *pa = *pb;
 *pb = tmp;
}
int main()
{
 int a = 10;
 int b = 20;
 printf("a = %d b = %d\n", a, b);
 Change(&a, &b);
 printf("a = %d b = %d\n", a, b);
 return 0;
}

2. By adding two shaping exchanging content.

int main()
{
 int a = 10;
 int b = 20;
 printf("a = %d b = %d\n", a, b);
 a = a + b;
 b = a - b;
 a = a - b;
 printf("a = %d b = %d\n", a, b);
 return 0;
}

For this algorithm, it has some flaws, that if these two numbers too large, then the two numbers add up to is likely to exceed the maximum value that can be stored in plastic, so this algorithm is not very good.
Similarly adder row can pass, then multiplying the number of the two should be, but this will be much easier than the maximum shaping.

int main()
{
 int a = 10;
 int b = 20;
 printf("a = %d b = %d\n", a, b);
 a = a*b;
 b = a/b;
 a = a/b;
 printf("a = %d b = %d\n", a, b);
 return 0;
}

3. By exchanging this content bitwise XOR shaping method. First look at the code:

int main()
{
 int a = 10;
 int b = 20;
 printf("a = %d b = %d\n", a, b);
 a = a^b;
 b = a^b;
 a = a^b;
 printf("a = %d b = %d\n", a, b);
 return 0;
}

We can understand, will a ^ b as a key, and that key and a bitwise exclusive-or you can get the original a, b and bitwise exclusive-or you can get the original b, then you can by this method achieve shaping of the exchange. And this algorithm does not exceed the maximum shaping, it is a good algorithm, but in practice the efficiency of this algorithm is not as efficient to create a temporary variable.

Published 20 original articles · won praise 9 · views 910

Guess you like

Origin blog.csdn.net/weixin_44915811/article/details/99698066