💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# Java 程序:使用按位 XOR 运算符交换两个数字 > 原文: [https://beginnersbook.com/2017/09/java-program-to-swap-two-numbers-using-bitwise-xor-operator/](https://beginnersbook.com/2017/09/java-program-to-swap-two-numbers-using-bitwise-xor-operator/) 这个 java 程序使用[按位 XOR 运算符](https://beginnersbook.com/2017/08/operators-in-java/)交换两个数字。在通过程序之前,让我们看看什么是按位 XOR 运算符:按位 XOR 比较两个操作数的相应位,如果它们相等则返回 1,如果它们不相等则返回 0。例如: ```java num1 = 11; /* equal to 00001011*/ num2 = 22; /* equal to 00010110 */ ``` `num1 ^ num2`比较`num1`和`num2`的相应位,如果它们不相等则生成 1,否则返回 0.在我们的例子中它将返回 29,相当于 00011101 让我们在 [Java](https://beginnersbook.com/java-tutorial-for-beginners-with-examples/) 程序中写一下: ## 示例:使用按位运算符交换两个数字 ```java import java.util.Scanner; public class JavaExample { public static void main(String args[]) { int num1, num2; Scanner scanner = new Scanner(System.in); System.out.print("Enter first number:"); num1 = scanner.nextInt(); System.out.print("Enter second number:"); num2 = scanner.nextInt(); /* To make you understand, lets assume I am going * to enter value of first number as 10 and second * as 5\. Binary equivalent of 10 is 1010 and 5 is * 0101 */ //num1 becomes 1111 = 15 num1 = num1 ^ num2; //num2 becomes 1010 = 10 num2 = num1 ^ num2; //num1 becomes 0101 = 5 num1 = num1 ^ num2; scanner.close(); System.out.println("The First number after swapping:"+num1); System.out.println("The Second number after swapping:"+num2); } } ``` **输出:** ```java Enter first number:10 Enter second number:5 The First number after swapping:5 The Second number after swapping:10 ```