Thursday, March 3, 2016

Know how to swap two numbers using XOR operation !

Dear Folks,
Perhaps you are familiar how to swap two numbers without using a temporary variable using arithmetic operation... like
let's swap , a =5 and b=7

step 1: a:=a+b
step 2: b:=a-b
step 3: a:=a-b

step 1: a:=5+7  i.e a:=12
step 2: b:=12-7 i.e b:=5
step 3: a:=12-5 i.e a=:7
We can see both got swapped...

Let's see how we can swap using EX-OR bit wise operator, let's use cap(^) operator to represent EX-OR operation:
Truth Table of EX-OR
step 1: a:=a^b
step 2: b:=a^b
step 3: a:=a^b

step 1: a:=5^7  
101  
111
----------                                                   
010   // Refer truth table of EX-OR 
i.e a:=2

step 2: b:=2^7
010
111
----------
101 i.e b:=5

step 3: a:=2^5
010
101
----------
111 i.e a:=7


Note: This is for your information, but these are not at all practically suitable methods, as they add computational overhead, So in practice we must use a method which uses a temporary variable, as at low level, it is just a data transfer.

Revert me back with queries... and suggestions
I hope you liked it ! let me know it by replying through this blog itsef....
Thanks for visiting, if you like the blog, please subscribe...

No comments:

Post a Comment