Home > C, C++, Javascript, MatLab, Python, Ruby > Swap two numbers w/o the temporary variable

Swap two numbers w/o the temporary variable


There are several tricks that will swap two variables without the need of a third variable for exchange value.

These following code are written in C/C++.

Trick #1: Using simple sum:

void Swap01(int *a, int *b)
{
	*a = *a + *b;
	*b = *a - *b;
	*a = *a - *b;
}

Trick #2: Using multiplication:

void Swap02(int *a, int *b)
{
	*a = *a * *b;
	*b = *a / *b;
	*a = *a / *b;
}

Trick #3: Using XOR

void Swap03(int *a, int *b)
{
	 *a ^= *b;
	 *b ^= *a;
	 *a ^= *b;
}

In general, the formula is:

a = a # b
b = a @ b
a = a @ b

whereas # and @ are inverses of each other.

Anyway, in some other programming language, it’s kinda short and looks interesting.

Ruby & Python:

a, b = b, a

PHP:

list($a, $b) = array($b, $a);

Javascript 1.7:

[a, b] = [b, a]

MATLAB:

[a,b] = deal(b,a);

Cheers,
Pete Houston

Advertisements
Categories: C, C++, Javascript, MatLab, Python, Ruby Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: