在学习.Net/C#或者任何一门面向对象语言的初期,大家都写过交换两个变量值,通常是通过临时变量来实现。本篇使用多种方式实现两个变量值的交换。
假设int x =1; int y = 2;现在交换两个变量的值。
使用临时变量实现
static void Main(string[] args){int x = 1;int y = 2;Console.WriteLine("x={0},y={1}",x, y);int temp = x;x = y;y = temp;Console.WriteLine("x={0},y={1}", x, y);Console.ReadKey();}
使用加减法实现
试想, 1+2=3,我们得到了两数相加的结果3。3-2=1,把1赋值给y,y就等于1; 3-1=2,把2赋值给x,这就完成了交换。
static void Main(string[] args){int x = 1;int y = 2;Console.WriteLine("x={0},y={1}",x, y);x = x + y; //x = 3y = x - y; //y = 1x = x - y; //x = 2Console.WriteLine("x={0},y={1}", x, y);Console.ReadKey();}
使用ref和泛型方法实现
如果把交换int类型变量值的算法封装到方法中,需要用到ref关键字。
static void Main(string[] args){int x = 1;int y = 2;Console.WriteLine("x={0},y={1}",x, y);Swap(ref x, ref y);Console.WriteLine("x={0},y={1}", x, y);Console.ReadKey();}static void Swap(ref int x, ref int y){int temp = x;x = y;y = x;}
如果交换string类型的变量值,就要写一个Swap方法的重载,让其接收string类型:
static void Main(string[] args){string x = "hello";string y = "world";Console.WriteLine("x={0},y={1}",x, y);Swap(ref x, ref y);Console.WriteLine("x={0},y={1}", x, y);Console.ReadKey();}static void Swap(ref int x, ref int y){int temp = x;x = y;y = x;}static void Swap(ref string x, ref string y){string temp = x;x = y;y = x;}
如果交换其它类型的变量值呢?我们很容易想到通过泛型方法来实现,再写一个泛型重载。
static void Main(string[] args){string x = "hello";string y = "world";Console.WriteLine("x={0},y={1}",x, y);Swap<string>(ref x, ref y)Console.WriteLine("x={0},y={1}", x, y);Console.ReadKey();}static void Swap(ref int x, ref int y){int temp = x;x = y;y = x;}static void Swap(ref string x, ref string y){string temp = x;x = y;y = x;}static void Swap<T>(ref T x, ref T y){T temp = x;x = y;y = temp;}
使用按位异或运算符实现
对于二进制数字来说,当两个数相异的时候就为1, 即0和1异或的结果是1, 0和0,以及1和1异或的结果是0。关于异或等位运算符的介绍在这里:http://www.cnblogs.com/darrenji/p/3921183.html
举例,把十进制的3和4转换成16位二进制分别是:
x = 0000000000000011;//对应十进制数字3
y = 0000000000000100; //对应十进制数字4
把x和y异或的结果赋值给x:x = x ^ y;
x = 0000000000000111;
把y和现在的x异或,结果赋值给y:y = y ^ x
y = 0000000000000011;
把现在的x和现在的y异或,结果赋值给x:x = x ^ y
x = 0000000000000100;
按照上面的算法,可以写成如下:
static void Main(string[] args){int x = 1;int y = 2;Console.WriteLine("x={0},y={1}",x, y);x = x ^ y;y = y ^ x;x = x ^ y;Console.WriteLine("x={0},y={1}", x, y);Console.ReadKey();}
"横看成岭侧成峰,远近高低各不同",在技术世界里,可能没有绝对的简单或复杂,再复杂的问题可以拆分成简单的模型;再简单的问题,从不同的角度看待,使用不同的方式实现,就多了更多的乐趣。
- 3楼Darren Ji
- @『大雪无痕』你说得也有道理。
- 2楼『大雪无痕』
- 推荐+1
- 1楼『大雪无痕』
- 还是 老老实实 的 用临时变量吧。,gt;使用 + - 都有 数值大小限制,(使用 ^ 或许 还行)。,gt;开辟一个 临时引用 或 临时值类型 占用的内存 和 CPU 远比调用一个 交换方法 消耗的资源 少得多,(当然,调用方法 可以少些 2行代码)。,,gt;现在很多面试题,总会问:不用中间变量,交换两个值:我只在答题纸上写下:不用中间变量的交换,都是装逼且 埋坑的 装逼行为。