How to swap two numbers without using a temporary variable? | GeeksforGeeks
How to swap two numbers without using a temporary variable?
Method 2 (Using Bitwise XOR)
http://www.geeksforgeeks.org/how-to-swap-two-variables-in-one-line/
C/C++:
How to swap two numbers without using a temporary variable?
Method 2 (Using Bitwise XOR)
if
(xp == yp)
// Check if the two addresses are same
return
;
x = x ^ y;
// x now becomes 15 (1111)
y = x ^ y;
// y becomes 10 (1010)
x = x ^ y;
// x becomes 5 (0101)
1) The multiplication and division based approach doesn’ work if one of the numbers is 0 as the product becomes 0 irrespective of the other number.
2) Both Arithmetic solutions may cause arithmetic overflow. If x and y are too large, addition and multiplication may go out of integer range.
3) When we use pointers to variable and make a function swap, all of the above methods fail when both pointers point to the same variable. Let’s take a look what will happen in this case if both are pointing to the same variable.
Method 1 (Using Arithmetic Operators)
int
x = 10, y = 5;
x = x + y;
// x now becomes 15
y = x - y;
// y becomes 10
x = x - y;
// x becomes 5
x = x * y;
// x now becomes 50
y = x / y;
// y becomes 10
x = x / y;
// x becomes 5
http://www.geeksforgeeks.org/how-to-swap-two-variables-in-one-line/
Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write “x, y = y, x”.
Java: The left hand operand is always evaluated before right hand operand
the expression “x ^= y ^= x ^= y;” doesn’t produce the correct result according to Java rules. It makes x = 0. However, we can use “x = x ^ y ^ (y = x);” Note the expressions are evaluated from left to right. If x = 5 and y = 10 initially, the expression is equivalent to “x = 5 ^ 10 ^ (y = 5);”C/C++:
// Swap using bitwise XOR (Wrong Solution in C/C++) x ^= y ^= x ^= y;
The above solution is wrong in C/C++ as it causes undefined behaviour (compiler is free to behave in any way). The reason is, modifying a variable more than once in an expression causes undefined behaviour if there is no sequence point between the modifications.
However, we can use comma to introduce sequence points. So the modified solution is
// Swap using bitwise XOR (Correct Solution in C/C++) // sequence point introduced using comma. (x ^= y), (y ^= x), (x ^= y);Read full article from How to swap two numbers without using a temporary variable? | GeeksforGeeks