使用按位异或运算符交换整数的 Java 程序


2022年4月20日, Learn eTutorial
1377

在这里,我们将解释如何编写一个 Java 程序,使用按位 **XOR** 运算符交换两个数字。

什么是按位 XOR 运算符?

按位运算符主要有六种。

  • &
  • |
  •  ^
  •  ~
  • <<
  • >>

按位运算符执行位级操作。按位 **XOR** 运算符 **^** 比较 **n1** 和 **n2** 的对应位(**n1 ^ n2**),如果对应位相等则返回 1,否则返回 0。

如何使用按位运算符实现 Java 程序来交换两个数字?

首先,我们需要声明类 **Swap**。将变量 **n1**、**n2** 声明为整数。将数字读入 **n1** 和 **n2**。然后使用按位 **XOR** 运算符交换数字,如下所示:

   n1 = n1 ^ n2;
   n2 = n1 ^ n2;
   n1 = n1 ^ n2;

然后使用 System.out.println() 函数显示 **n1** 和 **n2**。

假设 **n1** 为 10,**n2** 为 2。

那么   n1 = n1 ^ n2; 变为 1010 ^ 0010 = 0111

           n2 = n1 ^ n2; 变为 0111 ^ 0010 = 1010

            n1 = n1 ^ n2;  变为 0111 ^ 1010 = 0010

现在,**n1**=0010 表示 2,**n2**=1010 表示 10。

算法

**步骤 1**:使用 public 修饰符声明类 **Swap**。

**步骤 2**:打开 **main()** 开始程序,Java 程序执行从 main() 开始。

**步骤 3**:声明整数变量 **n1, n2**。

**步骤 4**:将第一个数字读入 **n1**。

**步骤 5**:将第二个数字读入 **n2**。

**步骤 6**:然后赋值 **n1=n1^ n2**,**n2=n1 ^ n2**,**n1=n1 ^ n2**。

**步骤 7**:然后使用 System.out.println() 函数显示交换后的数字 **n1** 和 **n2**。

Java 源代码

                                          import java.util.Scanner;
public class Swap{
    public static void main(String args[]){
        int n1,n2;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the first number:");
        n1= sc.nextInt();
        System.out.println("Enter the second number:");
        n2 = sc.nextInt();
         sc.close();
        n1 = n1 ^ n2;
        n2 = n1 ^ n2;
        n1 = n1 ^ n2;
      
        System.out.println("The First number after swapping is "+n1);
        System.out.println("The Second number after swapping is "+n2);
    }
}
                                      

输出

Enter the first number:5
Enter the second number:6
The First number after swapping is 6
The Second number after swapping is 5