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

 

Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s