swapping int numbers
we all know the simple swap function:
void swap(int &num1, int &num2)
{
int temp;
temp=num1;
num1=num2;
num2=temp;
}
fine and dandy. Just one problem, it declares an extra variable (temp).
How do you swap the numbers without that extra variable and, this is a big one, WITHOUT OVERFLOW?
I remember seeing something about this one time.
If you weren''t worried about overflow, you could do it like this:
num1+=num2;
num2=num1-num2;
num1-=num2;
I seem to remember something about ORs and XORs...
[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]
Make sure you are not swapping the same variables or you will screw the XORings
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement