Swap two numbers without using a temporary variable

Status
Not open for further replies.

PcEnthu

Linux Learner
Ok guys. Here is the problem. There are two variables x and y which hold numbers. You have to swap the value of the two variables. U might say, just store the value of x in a temporary variable z, store value of y in x and finally store z value in y :D Here is the tricky part, u have to do it without using the variable z
 
K

Kalyan

Guest
x,y be the nos.

1) x=x+y
2) y=x-y
3) x=x-y

u got them swapped.
 
OP
PcEnthu

PcEnthu

Linux Learner
@ all u guys, That was fast and u got that cracked that easily. Well done. I will try to come up with some level up questions later.
 

QwertyManiac

Commander in Chief
Or if you wish to do it the l33t way, use XOR.

Starting with x=10, y=20

x^=y
y^=x
x^=y

Now x=20 and y=10.
Logic's the same as addition mostly, except its bitwise. ;)

Edit: This a challenge or a homework question? :confused: For challenges, there exists a thread, I hope you can revive it with better questions than the ones already present.
 

Jove

Right off the assembly line
yeah...XORing is much better as compared to other suggested methods(here).
Other methods may not work if we are dealing with MAX possibles values of respective data types which results in overflow..so,
if(a!=b) ///if a==b, no need of swapping values
a^=b^=a^=b;
swaps the values in a and b

cheers :)
 

hariharan

Journeyman
i can do that in a single statement.. swap two number in w/o temp var


x ^= y ^= x ^= y;


This swaps the two varaibles... OF course in c and other languages which support bit wise operators..!!
 

ray|raven

Think Zen.
^Lolz, i missed that part :p
What was he thinking while writing it?

I've known guys who try to deduce logic from examples.
Crappy way, if you ask me. 99% of the time you end up with a logic that works only for the example.
 

Desi-Tek.com

In the zone
oh sorry i am awake from 24 hour :p

public
class Swap{
staticvoid swap(int x,int y){
//int temp=x;
x^=y; //2
y^=x; // 5
x^=y; //7
System.out.println("After swapping x = " + x + " y = " + y);
}
publicstaticvoid main(String[] args){
int x=5;
int y=7;

System.out.println("Before swapping x="+x+" y="+y);
swap(x,y);

}

}

//one line logic

public class Swap{
static void swap(int x,int y){
y=(x+y)-(x=y);
System.out.println("After swapping x= " + x + " y = " + y);
}
public static void main(String[] args){
int x=5;
int y=7;

System.out.println("Before swapping x="+x+" y="+y);
swap(x,y);

}
}
 
Last edited:
Status
Not open for further replies.
Top Bottom