美文网首页
使用按位异或做数据交换

使用按位异或做数据交换

作者: 杰克_王_ | 来源:发表于2021-08-10 15:37 被阅读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
*/

相关文章

网友评论

      本文标题:使用按位异或做数据交换

      本文链接:https://www.haomeiwen.com/subject/lttfbltx.html