Wednesday, January 19, 2011

Exchange two integer variables without using a temp variable

use the ^ operator which computes the bitwise exclusive (1^0 //1, 1^1//0, 0^0 //0, 0^1//1)

for instance:

int i=5;
int j=3;

We use:

i=i^j;
j=i^j;
i=i^j;

now i and j vablues are exchanged.

Because ^ operator matches the distributive law:
that is a ^ b=b^a

we can see:
i=i^j;
j=i^j^j=j^j^i=0^i=i;
i=i^j^i=i^i^j=0^j=j;

Another way is use the mathematic:

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

No comments: