4

Recently, I was faced with a question that asked me to swap variable values without creating an extra variable.

i.e. A = 10, B = 20. How store 20 to A and 10 to B?

The solution is:

A = A + B     #new value of A=30
B = B + A     #new value of B=50
A = B - A     #new value of A=20
B = B - 2 * A #new value of B=10

so A = 20 and B = 10

Does this algorithm have a known name?

12

That is a longer and less efficient variant of XOR swap algorithm. I'll just reiterate most-commonly known solutions here from the wiki:

# solution 1
A = A + B
B = A - B
A = A - B

# solution 2 (^ is XOR)
A = A ^ B
B = B ^ A
A = A ^ B

@PEMapModder

On the second last line, there is no difference between A^B and B^A right? Why swap them?

There is no difference between them. I think Wiki swaps them for historical reasons: For machine instructions that use 2 registers for binary operations (source and target/destination, unlike MIPS which uses 3 registers for binary ops), you would write the XOR solution as follows:

XOR A B       # A = A ^ B
XOR B A       # B = B ^ A
XOR A B       # A = A ^ B
  • 2
    What's wrong with A, B = B, A? That's how it works in a lot of the languages I am familiar with. – Jörg W Mittag May 17 '16 at 15:30
  • 1
    I think OP was challenged to find a solution to the problem without using parallel assignment. That would've been too easy. – mostruash May 17 '16 at 15:35
  • What "OP" means? – dellasavia May 17 '16 at 16:54
  • "Original Poster", ie, you. – Useless May 17 '16 at 16:58
  • 4
    Might be worth noting that the XOR solution should be immune to over-/under-flow, whereas solution 1 and OP's solution might be affected. – 8bittree May 17 '16 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.