4

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

Robin
  • 24,062
  • 5
  • 49
  • 58
ManMohan
  • 193
  • 1
  • 3
  • 13

5 Answers5

9

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
  • 3,041
  • 24
  • 17
  • 1
    If I remember correctly, though, this won't work if one of the values you're trying to swap is 0. – Anthony Oct 14 '10 at 13:13
  • And no, a value of zero is no problem at all. – Florian Mayer Oct 14 '10 at 13:22
  • 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 Oct 14 '10 at 14:06
  • @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 Oct 14 '10 at 14:41
1
private static void swap() {
    int a = 5;
    int b = 6;
    System.out.println("Before Swaping: a = " + a + " and b= " + b);
    // swapping value of two numbers without using temp variable and XOR bitwise operator
    a = a ^ b; // now a is 3 and b is 6
    b = a ^ b; // now a is 3 but b is 5 (original value of a)
    a = a ^ b; // now a is 6 and b is 5, numbers are swapped
    System.out.println("After  Swaping: a = " + a + " and b= " + b);

}

Output :

Before Swaping: a = 5 and b= 6
After  Swaping: a = 6 and b= 5
1
public class SwapNumbers {

 public static void main(String[] args) {

  int x = 11;
  int y = 22;

  System.out.println("Before Swapping");
  System.out.println("Value of x is :" + x);
  System.out.println("Value of y is :" + y);

  x = x + y;
  y = x - y;
  x = x - y;

  System.out.println("Before Swapping");
  System.out.println("Value of x is :" + x);
  System.out.println("Value of y is :" + y);
 }
}
Hemlata Gehlot
  • 341
  • 2
  • 12
-1
class Swap{

 int a;
 int b; 

 public static void main(String args[]){
    a = 10;
    b =20;
    System.out.println("******Before Swap*********");
    System.out.println("a= "+a);
    System.out.println("b= "+b);
    a = a + b;
    b = a - b;
    a = a - b;
    System.out.println("******After Swap*********");
    System.out.println("a= "+a);
    System.out.println("b= "+b);
 } 
}

Your Output will be :

******Before Swap*********
a= 10
b= 20
******After Swap*********
a= 20
b= 10

ritesh9984
  • 418
  • 1
  • 5
  • 17
-4

Using this ::

X = X ^ Y;
Y = X ^ Y;
X = X ^ Y;
*** ^ means XOR operation
Saiful
  • 1,891
  • 1
  • 15
  • 39