不使用第三个变量的交换两个数 (笔记)
Mar 4, 2014
typedef int SWAP_TYPE;
//交换两个数,不使用第三个变量
void swap(int &a,int &b,SWAP_TYPE type)
{
switch(type)
{
case 1:
//利用加减法(缺点:a+b可能溢出)
a = a + b;
b = a – b;
a = a – b;
break;
case 2:
//利用一个数异或本身等于0和异或运算符合交换率
a = a ^ b;
b = a ^ b;
a = a ^ b;
break;
case 3:
//乘除
a = a * b;
b = a / b;
a = a / b;
break;
case 4:
//不常见方法1
a = a + b – (b = a);
break;
case 5:
//不常见方法2
b = a + (a = b)*0;
break;
default:
break;
}
}