Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you swap two integer variables without using any if conditions, casting, or additional variables? [closed]

Tags:

swap

There are two integer variables. Can you swap those integer variables without using any if conditions, without casting, and without using additional variables? For example:

int a = 10;
int b = 5;

a > b always. The answer should be a == 5 and b == 10

like image 858
dotnet lover Avatar asked Jul 16 '10 06:07

dotnet lover


1 Answers

If you think you are being clever by not using 3rd variable then do some performance tests and you see that the much faster way is to use 3rd int to store the variable temporarily.

Anyways, i solved the problem with XOR bitwise operator:

a ^= b;
b ^= a;
a ^= b;
like image 159
Imre L Avatar answered Oct 21 '22 05:10

Imre L