Thursday, September 18, 2008

Tips #1: swap( a, b)

How do you swap two values in C/C++? General, we will create a function as below:

bool swap( int& value1, int& value2 )
{
int tempValue;
tempValue = value1;
value1 = value2;
value2 = tempValue;
return true;
}

Here comes the question. Can you swap these two values without using any temporary variable? For sure, you can swap two values without any temporary variable. Here is the solution,

bool swap( int& value1, int& value2 )
{
value1 ^= value2;
value2 ^= value1;
value1 ^= value2;
return true;
}

Any question?

No comments:

Post a Comment