exchange
-
Problem description : There are two numbers of A and B, and no additional variables can be defined, so as to realize the exchange of A and B values
-
For example : A = 3; B = 4; A = 4 after the exchange; B = 3;
-
Code:
- First use the amount as a variable
import java.util.Scanner;
public class TestDemo1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int A = scan.nextInt();
int B = scan.nextInt();
int tmp = A;
A = B;
B =tmp;
System.out.println("A = "+A+" B = "+B);
}
}
- No additional variables
import java.util.Scanner;
public class TestDemo1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int A = scan.nextInt();
int B = scan.nextInt();
A = A+B;
B = A-B;
A = A-B;
System.out.println("A = "+A+" B = "+B);
}
}