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.

Richard Miskin
  • 1,260
  • 7
  • 12
user3351552
  • 27
  • 1
  • 6

1 Answers1

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
Nima
  • 6,383
  • 7
  • 46
  • 68