Exercises-No extra space (variable) is needed, exchange the values of the two numbers

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:

  1. 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);
    }
}    
  1. 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);
    }
}

Guess you like

Origin blog.csdn.net/qq_45665172/article/details/111182967