Swipe 2 Numbers without using Third Variable or Temp Variable | Interview question

While giving interviews, Interviewers generally asks questions which tests logical thinking of candidate. This is one of the questions I faced while giving Interviews.

There are 2 ways through which you can swipe 2 numbers and it will gives you desired result.

Method 1:
Suppose X = 20 and Y = 10
Pseudo code for this is:

X = X + Y          // Hence, X will be 30
Y = X - Y          // Hence, Y will be 20
X = X - Y          // Hence, X will be 10

So this will swipe numbers.

Method 2:

Suppose X = 20 and Y = 10

Pseudo code for this is:

X = X + Y - (Y=X);

To elaborate this further, First X+Y will happen that makes things like below:

X = 30 - (Y = X)

Then,

Y = X        // Y will be 20

Hence,

 X = 30 - 20 =  10

 

Join Discussion

This site uses Akismet to reduce spam. Learn how your comment data is processed.