Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap two numbers without using temp variables or arithmetic operations?

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.

like image 474
Vishwanath Dalvi Avatar asked Sep 05 '10 18:09

Vishwanath Dalvi


People also ask

How do you swap without variables?

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.

How do you swap two numbers in python without using temporary variables?

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.


1 Answers

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

This is simple yet effective....

like image 53
sreejith k s Avatar answered Sep 25 '22 08:09

sreejith k s