How to swap two integer variables without using the third variable ?
See Solution: Swap two integer variables
I know three solutions, comment if you know more 🙂
Solution 1:
x = x+y; y = x-y; x = x-y;
Solution 2:
y = 2*((x+y)/2) – (x =y);
Solution 3:
x = x^y; y = x^y; x = x^y;
Note: However solution 1 & 2 has problem of overflow doing addition of two integers might overflow. But solution 3 will not have any such problem
Facebook Comments