In this tutorial, we will swap two numbers using XOR( ^ ) operator.
Before solving the solution, let’s examine what is a bitwise XOR operator. A bitwise XOR compares corresponding bits of two operands and returns 1 if they are equal and 0 if they are not equal.
Here is Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
class Program { static void Main(string[] args) { int number1 = 17; //number1 is equal as binary: 1 0 0 0 1; int number2 = 23; //number2 is equal as binary: 1 0 1 1 1; //number1 = 17 1 0 0 0 1 //number2 = 23 1 0 1 1 1 number1 = number1 ^ number2; //number1 becomes 6 = 0 0 1 1 0 //number1 = 6 0 0 1 1 0 //number2 = 23 1 0 1 1 1 number2 = number1 ^ number2; //number2 becomes 17 = 1 0 0 0 1 //number1 = 6 0 0 1 1 0 //number2 = 17 1 0 0 0 1 number1 = number1 ^ number2; //number2 becomes 23 = 1 0 1 1 1 Console.WriteLine("number 1 >:"+number1); Console.WriteLine("number 2 >:" + number2); Console.ReadLine(); } } |
Output:
1 2 3 4 5 6 7 |
//number1 (23) is equal as binary: 1 0 0 0 1; //number2 (17) is equal as binary: 1 0 1 1 1; number 1 > 17 number 2 > 23 |