General Question

Ranimi23's avatar

How can I swap two integers without temporary variables using JavaScript code?

Asked by Ranimi23 (1878 points ) October 16th, 2012

swap(var a, var b);

Observing members: 0 Composing members: 0

7 Answers

LostInParadise's avatar

This is a trick using the exclusive or operator ^ that was used when computers were short on memory.

a = (a ^ b) /* a^b, b */
b = (a ^ b) /* a^b, a */
a = (a ^ b) /* b, a */

You can also do it using subtraction for numeric values
a = a – b /* a – b, b */
b = b -a /* a-b, a */
a = b – a /* b, a */

LostInParadise's avatar

The second step for the subtraction should be b = a + b

Ranimi23's avatar

So it should be in JS:

a = a ^ b;
b = a ^ b;
a = a ^ b;

LuckyGuy's avatar

How about:
A = A + B
B = A – B
A = A – B

CWOTUS's avatar

You can’t forget that values of A and B are changing as you encounter these equations. So these equations would totally fail as “simultaneous equations”, but they work in series as the computer operates them.

A = A * B
B = A / B
A = A / B

So, for example, if you start out that A = 2; B = 7:
A = A * B = 2 * 7 = 14
B = A / B = 14 / 7 = 2
A = A / B = 14 / 2 = 7

phaedryx's avatar

side note:
although it is doable without a temporary variable, I find
var temp = a;
a = b;
b = temp;

much more obvious and I prefer obvious over clever most of the time when reading other people’s code.

LostInParadise's avatar

The advantage of using exclusive or for a computer is that there is no chance of overflow or, as in the case of division, loss of accuracy due to rounding.

Answer this question

Login

or

Join

to answer.

This question is in the General Section. Responses must be helpful and on-topic.

Your answer will be saved while you login or join.

Have a question? Ask Fluther!

What do you know more about?
or
Knowledge Networking @ Fluther