Swap 2 numbers without temporary variables

♠ Posted by GeekyFry in ,,,, at 8:45 PM

Write a function to swap two numbers without using temporary variables.


Possible Solution:
1
2
3
4
5
6
7
swap(a,b) {
 if (a != b) {
   a = a^b;
   b = a^b;
   a = a^b;
 }
}
Importance of if condition -
1. If a and b have the same value, it’s useless to swap them.
2. If a and b have the same reference, the XOR logic would fail.

0 comments:

Post a Comment