Tuesday, May 22, 2012

Most popular questions

1) Swap two values without a temp variable.

most common way is to use a temp variable as follows,
 temp = x;
x = y;
y = temp;

But you can use a simple trick to swap them without a explicit temp variable.

x=20; y=10;
x=x+y;  //x=30
y=x-y; //y=20;
x=x-y; //x=10;

It worked, nice trick keep in mind, interviewers like this question.

Also XOR operator can be used to Swap without a temp variable. XOR swap algorithm is as follows,

x = x XOR y
y = y XOR x
x = x XOR y

 

No comments:

Post a Comment