用异或运算进行两个值的交换

2017-08-25  本文已影响0人  superkun

什么是异或运算?就是不一样的位得1,一样的位得0。

交换两个数的值可以有这骚操作

#include <stdio.h>

int main()
{
    int a = 1;
    int b = 2;
    a^=b^=a^=b;
    printf("%d %d",a,b);
    return 0;
}

它是如何做到的呢?

先来看这样一个例子:

#include <stdio.h>

int main()
{
    int a = 1;
    int b = 2;
    a = a + b;
    b = a - b;
    a = a - b;
    printf("%d %d",a,b);
    return 0;
}

原理就是相加后减己得他。

再来看异或交换如何做到的

效率如何

#include <stdio.h>
#include <time.h>

int main()
{

    int n=2000000000;
    while(n--){
        int a = 12345678;
        int b = 23456789;
//        int t=a;
//        a=b;
//        b=t;

        a^=b^=a^=b;
    }
    printf("%f\n",(double)clock()/CLOCKS_PER_SEC);
    return 0;
}

加入第三个变量快一点点,以上数据分别为平均10s和平均12s。

那么问题来了含有负数的运算为什么也适用呢?

下次研究一下反码补码


参考《算法竞赛入门经典(第二版)》P9最下边小字。

上一篇 下一篇

猜你喜欢

热点阅读