最近看到一个问题感觉很有意思:
“如何在不申请临时变量的情况下交换两个数的值?”
思考许久没有思路,查阅一番发现方法不少,在这里介绍四种方法:
void swap(int *p, int *q)
{
*a = *a ^ *b;
*b = *b ^ *a;
*a = *a ^ *b;
}
提示:异或运算符 ^ 也称 XOR 运算符,它的规则是若参加运算的两个二进位同号,则结果为 0 (假);异号为 1(真)。即 0 ^ 0 = 0 , 0 ^ 1 = 1 , 1 ^ 0 = 1 , 1 ^ 1 = 0。
计算实例:
a = 3 -> 0000 0011
b = 4 -> 0000 0100
step1:
a = a ^ b
-> 0000 0011
^ 0000 0100
= 0000 0111 -> 7
step2:
b = b ^ a
-> 0000 0100
^ 0000 0111
= 0000 0011 -> 3
step3:
a = a ^ b
-> 0000 0111
^ 0000 0011
= 0000 0100 -> 4
void swap(int *p, int *q)
{
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
}
void swap(int *p, int *q)
{
*a = *a + *b - (*b = *a);
}
C/C++ 中 ( A = B ) 返回得到是赋值号( = )的左面的值
计算实例:
a = 3;
b = 4;
a = 3 + 4 - (b = 3)
= 3 + 4 - 3
= 4;
-> a = 4;
-> b = 3;
void swap(int *p, int *q)
{
*a ^= *b ^= *a ^= *b;
}
计算实例:
a = 3;
b = 4;
a = 3 ^ 4 = 7;
b = 4 ^ 7 = 3;
a = 7 ^ 3 = 4;
-> a = 4;
-> b = 3;