如何在没有第三个变量和没有算术运算符的情况下交换两个数字

时间:2010-10-14 13:10:25

标签: java

如何在没有第三个变量和没有算术运算符的情况下交换两个数字?

5 个答案:

答案 0 :(得分:6)

XOR是否算作算术运算符?如果没有,那么:

X := X XOR Y
Y := X XOR Y
X := X XOR Y

将此伪代码转换为编译的Java代码留给读者(关于'java'标记)。

答案 1 :(得分:0)

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);

}

输出:

Before Swaping: a = 5 and b= 6
After  Swaping: a = 6 and b= 5

答案 2 :(得分:0)

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);
 }
}

答案 3 :(得分:-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);
 } 
}

您的输出将是:

******在交换之前*********
a = 10
b = 20
******交换后*********
a = 20
b = 10

答案 4 :(得分:-4)

使用此::

X = X ^ Y;
Y = X ^ Y;
X = X ^ Y;
*** ^ means XOR operation