Swap the values of two integer
2017-12-24 本文已影响6人
成江
Method one, use a temp variable
int a = 10;
int b = 11;
int temp = a;
a = b;
b = temp;
Method two, arithmetic
int a = 10;
int b = 11;
a = a + b;
b = a - b;
a = a - b; // now b = a, which means a = a + b - a
The problem of this method is that it might overflow when a and b are very large. In other words, a + b is bigger than the range of int.
Method three, bit manipulation
int a = 10;
int b = 11;
a = a ^ b;
b = a ^ b; // Now, b = 10 ^ 11 ^ 11 = 10, coz 11 ^ 11 = 0, 10 ^ 0 = 10
a = a ^ b;
There is no overflow problem here. Moreover, we don't need a temp variable. Of course, the first method, it is much more straight forward and much easier to maintain.