Scala: Write a function to swap a number in place without using temporary variables

Your solution for C++ is not the best one, because it might cause integer overflow if a or b is big enough.

The right solution would be using xor:

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

But this kind of trick makes sense only if variables are mutable, so in your Scala version, you’d have to reassign function parameters to vars.

Another issue is, you should never do this in production code.
This algorithm is called xor swap and was beneficial on some early processors, but it’s not useful now. It gives you no benefit of better performance and is less readable that plainly using a temporary variable.

Leave a Comment