This equation swaps two numbers without a temporary variable, but uses arithmetic operations:
a = (a+b) - (b=a);
How can I do it without arithmetic operations? I was thinking about XOR.
Using arithmetic operatorsThe arithmetic operators for addition and subtraction can be used to perform the swap without using a third variable. Similarly, multiplication and division can be used to perform the swap without using the third variable.
To swap them without a temp variable, we need to add both numbers and store the result in the first one. Next, we've to subtract the second variable from the first one and save the result to the second one. Finally, we'll use the first variable to subtract from the second and also to store the result of this operation.
a=a+b; b=a-b; a=a-b;
This is simple yet effective....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With