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;

or

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

or

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

One thought on “How can you change two variables without temporary variable

  1. This fishing template is just great!! 🙂

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 )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: