tags:

views:

173

answers:

1

How can we swap two numbers without third variable and without arithmetic operator?

+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
If I remember correctly, though, this won't work if one of the values you're trying to swap is 0.
Shynthriir
XOR Swap cannot overflow.
Florian Mayer
And no, a value of zero is no problem at all.
Florian Mayer
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
@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