使用java编写并调试程序,要求从键盘录入两个整数,使用位运算符实现不通过第三个变量交换两个数
以下是使用位运算符实现不通过第三个变量交换两个数的Java代码:
import java.util.Scanner;
public class SwapWithoutTemp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the first integer: ");
int a = input.nextInt();
System.out.print("Enter the second integer: ");
int b = input.nextInt();
a = a ^ b; // XOR operation to get the sum of a and b without carry
b = a ^ b; // XOR operation to get the original value of a
a = a ^ b; // XOR operation to get the original value of b
System.out.println("After swapping, the first integer is " + a + " and the second integer is " + b);
}
}
该程序首先从键盘获取两个整数,然后使用三次异或运算(^)实现不通过第三个变量交换两个数。