1

I recently went to an interview and I was asked to write some code to swap the values of two variables without using third variable or any API.

I could not work out how to do this, can you help me on this?

For example I have two variable a=10 and b=20 the output should be b=10 and a=20.

0

1 Answer 1

1

Tricky but not that hard to figure out:

a = 10 b = 20 a = a + b; //a = 30, b = 20 b = a - b; //a = 30, b = 10 a = a - b; //a = 20, b = 10 
Sign up to request clarification or add additional context in comments.

6 Comments

adding 10 and 20 causes overflow?
Do we have any algorithm to swap.Here we are going with values.Suppose if we have to read the values from the keyboard and the with the swapped output mean how to solve @Nima
If instead of 20 you use Integer.MAX_VALUE you will get overflow. However, I think it all comes out in the wash and the values should be correct at the end.
this doesn't work with strings.. use XOR algorithmn as mentioned above
@PiotrMiazga XOR swap won't work for String either.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.