Monthly Archives: November 2012

How can you change two variables without temporary variable

This is one of my favourite interview questions. It’s a really simple question.

OK. Let’s see the typical wrong answer:

int a = 5;
int b = 6;

//store 'x' in a temp variable
int temp = a;
a = b;
b = temp;

This answer is wrong because it contains an unnecessary variable.

And there are some good solutions:

a = a * b;
b = a / b;
a = a / b;


a = a + b;
b = a - b;
a = a - b;


a ^= b;
b ^= a;
a ^= b;