I found new logic for this question, all know the using +,-,*,/ but this is something different logic. I used the electronic Ex-OR logic for swap two values. First understand how to use it.
Ex-OR Gate
Understand the table for input and output.
A | B | ANS |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
In this above table A and B are the inputs for the Ex-OR gate. If one of input is 1 then ans is 1 otherwise 0. If two inputs are same then ans like 1 then ans 1 or 0 then ans 0.
Example
A = 4 and B = 6.
In electronic all values used in binary like 0 and 1.
They used following way for values.
16 | 8 | 4 | 2 | 1 |
0 | 0 | 0 | 0 | 1 |
0 | 0 | 0 | 1 | 0 |
0 | 0 | 1 | 0 | 0 |
0 | 1 | 0 | 0 | 0 |
1 | 0 | 0 | 0 | 0 |
In this example we used A = 4 means in binary it is 00100
and B = 6 means in binary it is 00110.
In Programming it is used like this,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SwapValue
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Swapping of value using XOR");
Console.Write("Enter First Value - ");
var a = Convert.ToInt64(Console.ReadLine());
Console.Write("Enter Second Value - ");
var b = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("Values Before Swap A = {0} and B = {1}", a, b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
Console.WriteLine("Values After Swap A = {0} and B = {1}", a, b);
Console.ReadKey();
}
}
}
Output
Let us discuss how it works,
(1) a = a ^ b
A = 4 means 00100
B = 6 means 00110 now apply Ex-OR gate add this two binary values
when we add this binary values using first table ans is 00010 in binary and in decimal is a = 2.
(2) b = a ^ b
A = 2 means 00010 and B = 6 means 00110 now apply Ex-OR gate add this two binary values
when we add this binary values using first table ans is 00100 in binary and in decimal is b = 4.
(3) a = a ^ b
A = 2 means 00010 and B = 4 means 00100 now apply Ex-OR gate add this two binary values
when we add this binary values using first table ans is 01100 in binary and in decimal is a = 6.
In this way you can swap two values without third variable. I hope you find this blog useful. Thanks for reading.