DEV Community

Discussion on: Swapping two numbers, w/o a temp variable

Collapse
 
philnash profile image
Phil Nash

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”).

Collapse
 
kebby profile image
Tammo 'kb' Hinrichs • Edited

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
Collapse
 
philnash profile image
Phil Nash

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!

Thread Thread
 
kebby profile image
Tammo 'kb' Hinrichs

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

Thread Thread
 
hakash profile image
Morten Olsrud

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.

Collapse
 
peledzohar profile image
Zohar Peled

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.

Collapse
 
hakash profile image
Morten Olsrud

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 😊

Thread Thread
 
peledzohar profile image
Zohar Peled

Yeah, it is fun.