Tuesday, September 20, 2011

Swap two numbers without using temporary variable

Swap two numbers without using another variable 
 
function Swap (int x, int y)  
{
     if (x != y) {
         x = x + y;
         y = x - y;
         x = x - y;
     }
 }
 
 
Swap two numbers without using another variable using XOR
  
function xorSwap (int x, int y)  
{
     if (x != y) {
         x ^= y;
         y ^= x;
         x ^= y;
     }
 }

No comments:

Post a Comment