异或运算实现两数交换

1.异或定义

1 ⊕ 1 = 0

0 ⊕ 0 = 0

1 ⊕ 0 = 1

0 ⊕ 1 = 1

简单说就是,相同为0,不同为1。

 

2.C++实现方法

 1 #include <iostream>
 2 
 3 int main()
 4 {
 5       int a, b;
 6       std::cout << "请输入要交换的两个数:";
 7       std::cin >> a >> b;
 8       std::cout << "交换前:\na=" << a << "  b=" << b << "\n";
 9       if (a == b)
10       {
11       }
12       else
13       {
14             a = a ^ b;
15             b = a ^ b;
16             a = a ^ b;
17       }
18       std::cout << "交换后:\na=" << a << "  b=" << b << "\n";
19 
20       return 0;
21 }

 

posted @ 2017-03-29 17:46  flatcc  阅读(324)  评论(0编辑  收藏  举报