Page 1 of 1

How to swap two variables... ??

Posted: Tue Mar 13, 2007 10:05 am
by pipo
hi all...

I got a quiz...

How to swap two variables ???

only use two variables and two statements...

In general, the code is following...

Code: Select all

temp = a;
a = b;
b = temp;
how to swap two variables using only two variables and two statements ?? do not use a temporary variable.. and 3 statements...

Posted: Wed Mar 14, 2007 1:24 am
by Leonid
Using bitwise operators you can do it like this:

Code: Select all

a ^= b ^= a ^= b;
Though I usually use STL provided swap function because it is faster to type and is more comprehentable, like that:

Code: Select all


Posted: Thu Mar 15, 2007 2:24 am
by pipo
First of all, Thanks for your reply...

I suggested you have to use just 2 statements..

it means you must use 2 equal signs...

I know using bitwise operators suggested by Leonid..

I'm sorry but it's not the wanted answer

PS.. Sorry for poor english :(

Posted: Sun Mar 18, 2007 12:15 am
by misof
If you can only do one assignment in one statement, it seems impossible -- after the first assignment, one of the variables is unchanged, the other has to have the new value, and thus one of the values is lost.

I think we need a more precise definition of what those "two statements" are allowed to be.

Code: Select all

void swap(int &a, int &b) {
  if (a>b) a--, swap(a,b), b++;
  if (a<b) b--, swap(a,b), a++;
can be considered to be two statements, and with no equal signs :D

If you don't like the if-s, you may go one step further:

Code: Select all

void swap(int &a, int &b) {
  (a>b) && (a--, swap(a,b), b++);
  (a<b) && (b--, swap(a,b), a++);
Aren't those two C++ statements? :wink:


Posted: Mon Mar 19, 2007 9:15 pm
by QulinXao
buty of arifmetica is
function swap(var a,b:T):T;begin

or on array a[0..1]

for i:=0 to 2 do a:=-(a[0]+a[1]);