不使用第三个变量交换两个数字

交换两个数字:

 1 using System;
 2 
 3 namespace ConsoleApplication
 4 {
 5     class Program
 6     {
 7         static void Main(string[] args)
 8         {
 9             // 交换2个数字的方法
10 
11             int a = 3, b = 5;
12             int c = 0;
13 
14             // 方法1:借助第三方临时变量
15             // 有点:阅读性强,开发时使用.
16             Console.WriteLine("before switch: a={0},b={1},c={2}", a, b, c);
17 
18             c = a;
19             a = b;
20             b = c;
21 
22             Console.WriteLine("after switch: a={0},b={1},c={2}", a, b, c);
23 
24             // 方法2: 求和:根据总和得之各个变量的值
25             // 去点:如果两个数值过大,会超出int范围,溢出。
26             // 不需要第三方变量交换2个数字
27             Console.WriteLine("before switch: a={0},b={1}", a, b);
28             a = a + b;
29             b = a - b;
30             a = a - b;
31             Console.WriteLine("after switch: a={0},b={1}", a, b);
32 
33 
34             // 方法3:位运算之异或
35             // 规律:一个数异或同一个数2次,结果还是这个数.
36             // 缺点:阅读性差
37             Console.WriteLine("before switch: a={0},b={1}", a, b);
38             a = a ^ b;
39             b = a ^ b;
40             a = a ^ b;
41             Console.WriteLine("after switch: a={0},b={1}", a, b);
42 
43             Console.WriteLine(2 << 3);
44 
45             Console.ReadKey();
46         }
47     }
48 }
原文地址:https://www.cnblogs.com/fanyong/p/2829857.html