Yahoo Interview Question
Software Engineer / Developersa) int temp=a;
a=b;
b=temp;
b) a=(a+b)-(b=a)
c) a^=b^=a^=b
The first method can be used even with user defined type however, it takes a temp variable.
The second method doesn't work with user defined types as arithmetic is not possible in case of user defined types.. However, after overloading arithmetic operator[like in C++], it is possible.
The third method is the best as it works on the bits at H/W level & thus doesn't require any temporary register. It thus, guarantees faster operation. However, it fails when the situation needs swapping user defined types.
Actually, XOR requires 3 times of xor operations and 3 times of assignment.
Using tmp requires 3 times of assignment.
Of course it uses a variable but normally it is 4 bytes even it is integer or pointer. (or 8 bytes)
XOR normally doesn't support many types except int (or ambiguous, depending on language)
Using tmp is easier to make template inline function.
And much more readable.
So I prefer Using tmp than Using XOR.
I think the best is the XOR implementation, reason being:
- dronzer709 June 21, 2011when u use temp variable memory is used more and you access the register every now and then, when you are doing arithmetic operation you incure the overhead of ALU (hardware circuit) but bitwise operation is manipulation of bits at hardware level as the bits are already in the register which is fastest of three.