6

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

Mat
  • 202,337
  • 40
  • 393
  • 406
dotnet lover
  • 91
  • 2
  • 9

6 Answers6

14

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;
Imre L
  • 6,159
  • 24
  • 32
  • More about swapping with xor is here http://en.wikipedia.org/wiki/XOR_swap_algorithm – Developer Marius Žilėnas Jan 06 '14 at 08:56
  • This fails to work if `a == b`. – Axoren Nov 22 '14 at 16:57
  • What language are you using? – Imre L Nov 24 '14 at 13:08
  • @Axoren: no, it does not fail. – Doc Brown Jan 20 '15 at 12:39
  • My mistake. It fails if `a` and `b` are references to the same variable, not if they're the same value. For example: `int c; int *a = &c; int *b = &c;`. In this case, `*a ^= *b` will cause both `*a` and `*b` to become 0 at the same time, leading to the value being lost. This is still important to note if attempting to implement a swap method that works with the variable's addresses. – Axoren Jan 20 '15 at 20:24
  • In fact, all of the answers to this question fail under that case. I think that should be part of an interview question. – Axoren Jan 20 '15 at 20:26
  • 1
    Your example "fails" because you have the variables pointing to same memory location. This is not in the scope of question – Imre L Jan 22 '15 at 09:42
11
a=a+b;
b=a-b;
a=a-b;
Doc Brown
  • 19,739
  • 7
  • 52
  • 88
4

It's a little trick.

int a = 5;
int b= 10;
a = a+b;
b = a-b; /* Really (a+b) - b i.e. a */
a = a-b; /* Really (a+b) - a i.e. b */
Matt Mitchell
  • 40,943
  • 35
  • 118
  • 185
3

yes you can do it By using plus/minus operation.

Example:
num1 = num1 + num2;                
num2 = num1 - num2;                
num1 = num1 - num2;
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
3
a=a+b
b=a-b
a=a-b

That's it!

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Mayur
  • 3,063
  • 10
  • 42
  • 55
3

simple try this

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

and that's it

Johnny
  • 1,555
  • 3
  • 14
  • 23