多方法实现 swap 2 个 int 变量的值

最常用方法是用临时变量保存备份值

void swap(int &x, int &y)
{
    int temp = x;
    x = y;
    y = temp;
}

不使用临时变量,方法是:按位异或 及 四则运算实现

#include <iostream>
#include <limits>
using namespace std;
void swap(int &x, int &y)
{
    x ^= y;
    y = x ^ y;
    x = x ^ y;
}
void swap1(int &x, int &y)
{
    x = x + y; // 即使溢出,结果仍正确
    y = x - y;
    x = x - y;
}
void swap2(int &x, int &y)
{
    x = x - y; // x - y 丢失数据
    y = x + y;
    x = x + y;
}
void swap3(int &x, int &y)
{
    x = x * y; // x*y 可能溢出
    y = x / y;
    x = x / y;
}
void swap4(int &x, int &y)
{
    x = y / x;
    y = y / x; // x = 0 出错
    x = x * y;
}
 int main(void)
{
    int x = numeric_limits<int>::max();
    int y = numeric_limits<int>::max()-1;

    // x = 1, y = 2;
    cout << "原值" << x << " " << y << endl;

    swap(x, y);
    swap(x, y);
    cout << "swap 异或:";
    cout << x << " " << y << endl;

    swap1(x, y);
    swap1(x, y);
    cout << "swap 加:";
    cout << x << " " << y << endl;

    swap2(x, y);
    swap2(x, y);
    cout << "swap 减:";
    cout << x << " " << y << endl;

    // swap3(x, y);
    // cout << "swap 乘:";
    // cout << x << " " << y << endl;

    // swap4(x, y);
    // cout << "swap 除:";
    // cout << x << " " << y << endl;

    cout << "===========" << endl;
    x = numeric_limits<int>::min();
    y = numeric_limits<int>::min()+1;
    cout << "原值" << x << " " << y << endl;
    swap(x, y);
    swap(x, y);
    cout << "swap 异或:";
    cout << x << " " << y << endl;

    swap1(x, y);
    swap1(x, y);
    cout << "swap 加:";
    cout << x << " " << y << endl;

    swap2(x, y);
    swap2(x, y);
    cout << "swap 减:";
    cout << x << " " << y << endl;
}

运行结果为:

原值2147483647 2147483646
以下交换使用一种方法均进行交换2次,如仍输出原值,结果正确
swap 异或:2147483647 2147483646
swap 加:2147483647 2147483646
swap 减:-2147483647 -2147483648
===========
原值-2147483648 -2147483647
swap 异或:-2147483648 -2147483647
swap 加:-2147483648 -2147483647
swap 减:2147483646 2147483647
[Finished in 0.4s]

由以上结果分析,只有通过按位异或的方式和用一个变量保存和(虽然溢出但结果正确)的方式能正确实现交换。

// 异或
void swap(int &x, int &y)
{
    x ^= y;
    y = x ^ y;
    x = x ^ y;
}
// 用 x 保存 x+y 的和
void swap1(int &x, int &y)
{
    x = x + y;
    y = x - y;
    x = x - y;
}

其他方式,如通过保存2个变量的差/积/商,对于某些数据可能输出正确结果,但是对于可能溢出的数据,不能实现正确的交换

结论

除了使用临时变量实现交换的方法外,还可以用按位异或 和 用其中一个变量保存和的形式实现交换2个整型变量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值