不使用中间变量交换两个数


 

第一种用数学思维,第二种用异或

如交换a,b

1:    a=a+b;

       b=a-b;

       a=a-b;

2:    a=a^b;

       b=b^a;

       a=a^b;


 

代码:

  

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{

    int a,b;
    cin>>a>>b;
    a=a+b;
    b=a-b;
    a=a-b;
    cout<<a<<" "<<b<<endl;
    a=a^b;
    b=a^b;
    a=a^b;
    cout<<a<<" "<<b<<endl;
    return 0;
}

  

posted @ 2016-06-10 21:53  Zeroinger  阅读(174)  评论(0编辑  收藏  举报
无觅关联推荐,快速提升流量