1. Swapping two numbers without using temp variable in Java
int a = 10;
int b = 20;
System.out.println("value of a and b before swapping, a: " + a +" b: " + b);
//swapping value of two numbers without using temp variable
a = a+ b; //now a is 30 and b is 20
b = a -b; //now a is 30 but b is 10 (original value of a)
a = a -b; //now a is 20 and b is 10, numbers are swapped
System.out.println("value of a and b after swapping, a: " + a +" b: " + b);
2. Swapping two numbers without using temp variable in Java with the bitwise operator
int a = 2; //0010 in binary
int b = 4; //0100 in binary
System.out.println("value of a and b before swapping, a: " + a +" b: " + b);
//swapping value of two numbers without using temp variable and XOR bitwise operator
a = a^b; //now a is 6 and b is 4
b = a^b; //now a is 6 but b is 2 (original value of a)
a = a^b; //now a is 4 and b is 2, numbers are swapped
System.out.println("value of a and b after swapping using XOR bitwise operation, a: " + a +" b: " + b);
3. Swapping two numbers without using temp variable in Java with division and multiplication
int a = 6;
int b = 3;
System.out.println("value of a and b before swapping, a: " + a +" b: " + b);
//swapping value of two numbers without using temp variable using multiplication and division
a = a*b; //now a is 18 and b is 3
b = a/b; //now a is 18 but b is 6 (original value of a)
a = a/b; //now a is 3 and b is 6, numbers are swapped
System.out.println("value of a and b after swapping using multiplication and division, a: " + a +" b: " + b);
您还可以执行以下操作:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter x:");
int x = scanner.nextInt();
System.out.println("Enter y:");
int y = scanner.nextInt();
System.out.println("Before swap: x=" + x + ", y=" + y);
x = x + y;
y = x - y;
x = x - y;
System.out.println("After swap: x=" + x + ", y=" + y);
}
}
# 1 楼答案
我将列出三种不同的技术,您可以使用它们来交换两个数字,而无需在Java中使用temp变量:
您还可以执行以下操作: