习题——不需要额外空间(变量),交换俩个数的值

交换

  • 问题描述:现在有A和B俩个数,不能定义额外的变量,从而实现对A和B值的交换

  • 例如:A = 3;B = 4;交换之后A = 4;B = 3;

  • 代码实现:

  1. 首先使用额为变量
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. 不使用额外变量
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);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45665172/article/details/111182967