re: Swapping two numbers, w/o a temp variable VIEW POST


What if summing a and b leads to a number that is larger than the maximum integer? This would cause an overflow.

I’d hate for an interview trick like this to lead to real world problems. This is the same issue that was present in every incorrect binary search function (see “implementation issues”).


Totally agree. Interview tricks should never find their way into production code. In fact, I think that's one of the worst problems in software development technical interviews today - the fact that the problems asked and the solutions expected are in no way applicable in real world situations.


Couldn't agree more, but because they do, and because we love Code Wars and similar code quiz sites, discussing these tricks are still needed, and for me at least, fun 😊


That's why you usually use XOR for the swap trick :)

a^=b;  // a' = (a^b)
b^=a;  // b' = b ^ (a') = b ^(a^b) = a
a^=b;  // a'' = a' ^ b' = (a^b)^a = b

Yeah, but not in real code! I'd prefer it were readable over assigning one extra variable. You've got to find some specific conditions to make this the better code to use!

I actually used this in real code once, in an assembly inner loop where I was really running out of registers :), but you're right of course.

Related question: Did anyone here ever have to reverse a string? :D

Not in an interview, but in a quiz somewhere. It was an entry level one so only restriction was to not use the built in functions.

code of conduct - report abuse