Welcome to MindCipher, a social repository of the world's greatest brain teasers, logic puzzles and mental challenges.

Swap Variables in Place without XOR

Suppose you have two variables, a and b. How can you swap their values without using a temporary variable and also without using the bitwise operator XOR?

See solution.

In a similar manner to the XOR solution, we can use simple addition and subtraction:

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

Comments


Mehul Thakkar

Now, can you think about swapping 3 variables(for ex. input,a=5,b=10,c=15 then output, a=15,b=5 and c=10) applying same rules as in this question

  

Jay

Using the method above, swap a and c first and then swap b and c


sandeep

solution: a=a+b; b=a-b; a=a-b; example: a=2,b=3 a=2+3; (a=5) b=5-3; (b=2) a=5-2; (a=3) now a=3,b=2


Jay

Can also be done as:

a = a/b
b = a*b
a = b/a

NOTE: does not work if a or b is 0


Chaitanya Dwivedi

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

Example: a = 7 b = 3

Example: a = 7+3 = 10 b = 10-3 = 7 a = 10-7= 3

  

Ravi

Yep, that's exactly the solution provided.


Cddc

a = (a + b)/2 b = a - b

a = a - b b = a + 2b

Another messy solution, but works.


Abhinav

Why think so uch , when you can use multiple assignment operators :| b=a+b-(a=b);


lalitha

a=a+b-(b=a) this is single line swapping with out using third variable


Alex Pinkney

use Python:

a, b = b, a

easy!

Check out other puzzles:
Random  

Like this? You might also like:
A Pharmacist's Nightmare
Running Race
Attic Light Switch
Submitted by
Valentin
over 1 year ago
Likes
Difficulty 4.0 ?

Tags
Math Computer Science


Back