📜  程序在C#中使用XOR运算符交换数字

📅  最后修改于: 2021-05-29 21:17:45             🧑  作者: Mango

C#程序使用按位XOR操作交换两个数字。给定x和y两个变量,使用XOR语句交换两个变量。

例子:

Input: 300 400 

Output: 400 300 

Explanation: 
x = 300 y = 400 
x = 400 y = 300
C#
// C# Program to Swap the two Numbers
// using Bitwise XOR Operation
using System;
using System.Text;
  
namespace Test {
class GFG {
    
  static void Main(string[] args) {
    int x, y;
    Console.WriteLine("Enter two numbers \n");
    x = int.Parse(Console.ReadLine());
    y = int.Parse(Console.ReadLine());
  
    // printing the numbers before swapping
    Console.WriteLine("Numbers before swapping");
    Console.WriteLine("x = {0} \t b = {1}", x, y);
  
    // swapping
    x = x ^ y;
    y = x ^ y;
    x = x ^ y;
  
    // printing the numbers after swapping
    Console.WriteLine("Numbers after swapping");
    Console.WriteLine("x = {0} \t b = {1}", x, y);
  
    Console.ReadLine();
  }
}
}


输出:

Enter two numbers 

Numbers before swapping
x = 300      b = 400
Numbers after swapping
x = 400      b = 300