-1

How to swap 2 integers without using a third variable such that it works for all ranges of integers. I know that generally we do the following logic.

        int a, b;

        a = 10;
        b = 30;
        a = a + b;
        b = a - b;
        a = a - b;

But this logic will fail if (a + b) gives the value more than the integer range. Is there any other logic?

Phoenix
  • 1,045
  • 1
  • 14
  • 22
ismail baig
  • 861
  • 2
  • 11
  • 39
  • you might want to refer to this post: http://stackoverflow.com/questions/26274628/how-do-you-swap-two-integer-value-without-using-temp-variable – Hatjhie Oct 10 '14 at 02:03

3 Answers3

2

I believe you're looking for the XOR swap:

if (a != b) {
    a ^= b;
    b ^= a;
    a ^= b;
}
bmat
  • 2,084
  • 18
  • 24
1

You can use xor ...

x ^= y;
y ^= x;
x ^= y;

Source with a handy live demo.

Ricky Smith
  • 2,379
  • 1
  • 13
  • 29
1
int a=10;
int b=20;

a=a^b;
b=a^b;
a=a^b;
Console.WriteLine(a);
Console.WriteLine(b);
Vikas Gupta
  • 4,455
  • 1
  • 20
  • 40