I recently read the trick about swapping two int values with no temp variable (the XOR trick), but I discovered that that does not work with floats. Is there a way to swap two float variables with no temp variable?
I don't have a specific counterexample but I am willing to bet that for sufficiently extreme values of the two floats (close to the maximum possible float value, close to the minimum possible float value, or so far apart in range that N1 + N2 = N1 and N2 <> 0) that doesn't work.
Actually, now that I reread your post, even the example you provided didn't work! [ January 24, 2008: Message edited by: Paul Clapham ]
We all read your post. It's a good technique, but as your output showed, and as Paul Clapham pointed out, it has roundoff errors. So now we are discussing ways to swap the exact values. Try swapping 0.0000001F and 1000000. Or swapping 1 and Float.POSITIVE_INFINITY.
Joined: Mar 22, 2005
Originally posted by ankur rathi: These kinda tricks are asked in interviews, no use in real project.
I hope everybody knows enough to avoid companies that think that this sort of question is suitable for interviews.