How can we swap two numbers without third variable and without arithmetic operator?
views:
173answers:
1
+2
A:
Does XOR count as an arithmetic Operator? If not, then:
X := X XOR Y
Y := X XOR Y
X := X XOR Y
Converting this pseudo-code to Java code that compiles is left as an exercise to the reader (with regards to the ‘java’ tag).
Florian Mayer
2010-10-14 13:11:28
If I remember correctly, though, this won't work if one of the values you're trying to swap is 0.
Shynthriir
2010-10-14 13:13:35
XOR Swap cannot overflow.
Florian Mayer
2010-10-14 13:18:02
And no, a value of zero is no problem at all.
Florian Mayer
2010-10-14 13:22:34
Funny, I always thought that XOR was arithmetic, but at least it isn't the +, -, *, or / operators the poster is probably thinking about.
Edwin Buck
2010-10-14 14:06:34
@Edwin, @Florian: XOR is a bitwise operator, so this fits the given requirements. @Shynthriir: 0 is fine, but it *is* a problem if X and Y refer to the same location in memory.
Michael Madsen
2010-10-14 14:41:23