使用按位异或做数据交换
2021-08-10 本文已影响0人
杰克_王_
using System;
using System.Diagnostics;
namespace ExchangeDemo {
class Program {
static void Main (string[] args) {
Random random = new (Environment.TickCount);
for (var x = 0; x < int.MaxValue; x++) {
int y = random.Next ();
var (X, Y) = Exchange (x, y);
Console.WriteLine ($"{x}<=>{y} => {X}, {Y}");
Debug.Assert (x == Y && y == X);
}
}
static (int X, int Y) Exchange (int x, int y) {
x ^= y;
y = x ^ y; // y = (x ^ y) ^ y
x ^= y; // x = (x ^ y) ^ x
return (x, y);
}
}
}
/*
设 x = 1, y = 2, 即 x = 01, y = 10
则 z = x ^ y = 01 ^ 10 = 11
z ^ y = 11 ^ 10 = 01 = x
z ^ x = 11 ^ 01 = 10 = y
*/