两个变量值交换的方法

借助其他变量

引入temp暂存其中一方的值

void swap(int &a,int &b)
{
    int temp;
    temp=a;
    a=b;
    b=temp;
}

不借助其他变量

加法

void swap(int &a,int &b)
{
    a=a+b;
    b=a-b;
    a=a-b;
}

缺点:注意加法不要溢出

乘法

void swap(int &a,int &b)
{
    a=a+b;
    b=a-b;
    a=a-b;
}

缺点:注意加法不要溢出

异或

void swap(int &a,int &b)
{
    a=a^b;
    b=a^b;
    a=a^b;
}

优点:无需考虑溢出

猜你喜欢

转载自www.cnblogs.com/wwj321/p/12327072.html