当前位置:网站首页>[day 18] given two variables A and B, exchange their values | three solutions

[day 18] given two variables A and B, exchange their values | three solutions

2022-06-09 16:18:00 Executory peduncle

This article has been included in the column
《Java Introduction 100 cases 》

order 、 Column Preface

   This column opens , The purpose is to help everyone better master learning Java, Especially some Java Learners' It is difficult to find systematic algorithm learning materials on the Internet to help you get started with algorithms , At the same time, if you have any questions about the contents of the column, you can add my wechat at the end of the article to give you a one-to-one explanation .
   But the most important thing is to think independently , For all the content of this column , Be able to fully master , Write the code completely by yourself , There must be no problem getting started with the algorithm .
   The learning of algorithm must not be short of summary , Here I recommend that you can go to University algorithm community Punch in the learned knowledge , To consolidate and review .
   The only way to learn algorithms well must be Topic sea strategy , Only by accumulating a lot of practice can you practice your skills . Any topic of the column I will start with 【 Title Description 】【 Their thinking 】【 Template code 】【 Code parsing 】 Wait for four plates to explain .

order 、 Preface of this chapter

   Exchange the values of two variables , This is a very common demand , But most people only know how to exchange temporary variables , This is also a common method . But in today's era of involution , This can also be used as a test point for the interview , You are not allowed to use temporary variables to ask you how to exchange the values of two variables . Today we will also talk about the three most commonly used methods .

One 、【 Example 1】

1、 Title Description

   Given multiple sets of test data , Give two variables at a time a , b a,b a,b, Please exchange the values of two variables , And print their values . ( − 2147483647 ≤ a , b ≤ 2147483647 ) (-2147483647 \le a,b \le 2147483647) (2147483647a,b2147483647)

2、 Their thinking

   stay Java There is no ready-made function in to exchange values between two variables . But it's easy to do this . For example, you have two glasses of water a and b, Let you exchange two cups of water . You'll think of what to do ? It must be another empty cup c, The first a Pour in c, And then b Pour in a, Last c pour b that will do . The same is true of the most naive method of exchanging variables .

3、 Template code

1、 Temporary variable method

import java.util.Scanner;
public class Main{
    
    public static void main(String[] args) {
    
        Scanner sc=new Scanner(System.in);
        while (sc.hasNext()){
    
            int a=sc.nextInt();
            int b=sc.nextInt();
            int c=0;
            c=a;
            a=b;
            b=c;
            System.out.println(a+" "+b);
        }
    }
}
  • ( 1 ) (1) (1)c=a, hold a a a The value of c c c
  • ( 2 ) (2) (2)a=b, hold b b b The value of a a a
  • ( 3 ) (3) (3)b=c, hold c c c The value of b b b, and c c c At the very beginning a a a Value .
  • This completes the variable exchange task .

2、 Arithmetic operation

import java.util.Scanner;
public class Main{
    
    public static void main(String[] args) {
    
        Scanner sc=new Scanner(System.in);
        while (sc.hasNext()){
    
            long a=sc.nextLong();
            long b=sc.nextLong();
            a=a+b;//(1)
            b=a-b;//(2)
            a=a-b;//(3)
            System.out.println(a+" "+b);
        }
    }
}
  • ( 1 ) (1) (1) When a=a+b After execution ,a The value of is updated to a+b And .
  • ( 2 ) (2) (2) When b=a-b After execution ,b The value of a a+b-b, At the beginning a Value .
  • ( 3 ) (3) (3) Last a=a-b After execution ,a The value of a a+b-a, At the beginning b Value .
  • ( 4 ) (4) (4) Because the data range is too large ,a+b The operation of may explode int, So we need to use long.
  • This completes the variable exchange task .

3、 XOR exchange method

   Here's one of the most amazing exchange methods —— XOR exchange method .^ Symbol is an operation in bit operation . For binary of two numbers , If the same bit is different, it is 1, The same thing 0. So the XOR operation has the following important properties :

  • 1 ) 1) 1) The result of two identical numbers exclusive or is 0.
  • 2 ) 2) 2) Any number and 0 The result of XOR is itself
  • 3 ) 3) 3) XOR operation satisfies the combination law and commutative law
  • 4 ) 4) 4) When a^b=c when , There are also a^c=b and b^c=a.
import java.util.Scanner;
public class Main{
    
    public static void main(String[] args) {
    
        Scanner sc=new Scanner(System.in);
        while (sc.hasNext()){
    
            int a=sc.nextInt();
            int b=sc.nextInt();
            a=a^b;
            b=a^b;
            a=a^b;
            System.out.println(a+" "+b);
        }
    }
}
  • ( 1 ) (1) (1) When a^b We'll get a result c, here a be equal to c.
  • ( 2 ) (2) (2) When b=a^b when , That is to say b=c^b, here b The value of becomes the first a.
  • ( 3 ) (3) (3) When a=a^b when , That is to say a=a^c, here a The value of becomes the first b.
  • This completes the variable exchange task .
     Insert picture description here

4、 Comparison of the three methods .

   Method 1 It's the most commonly used , Method 2 Defective not recommended , Method 3 Need to understand and master , But it is not recommended to use at ordinary times , Because the readability is not good , Some people don't understand what this code is about . Therefore, it is recommended to use 1.

3、 ... and 、 Recommendation column

《 Zero fundamental algorithm 100 God 》

Four 、 After-school exercises

Serial number Topic link Difficulty rating
1 Exchange numbers 1
There are questions about learning ?
原网站

版权声明
本文为[Executory peduncle]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091545385204.html