当前位置:网站首页>[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】
Learning Guide
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) (−2147483647≤a,b≤2147483647)
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+bAfter execution ,aThe value of is updated toa+bAnd . - ( 2 ) (2) (2) When
b=a-bAfter execution ,bThe value of aa+b-b, At the beginningaValue . - ( 3 ) (3) (3) Last
a=a-bAfter execution ,aThe value of aa+b-a, At the beginningbValue . - ( 4 ) (4) (4) Because the data range is too large ,
a+bThe operation of may explodeint, So we need to uselong. - 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
0The result of XOR is itself - 3 ) 3) 3) XOR operation satisfies the combination law and commutative law
- 4 ) 4) 4) When
a^b=cwhen , There are alsoa^c=bandb^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^bWe'll get a resultc, hereabe equal toc. - ( 2 ) (2) (2) When
b=a^bwhen , That is to sayb=c^b, herebThe value of becomes the firsta. - ( 3 ) (3) (3) When
a=a^bwhen , That is to saya=a^c, hereaThe value of becomes the firstb. - This completes the variable exchange task .

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
Four 、 After-school exercises
| Serial number | Topic link | Difficulty rating |
|---|---|---|
| 1 | Exchange numbers | 1 |
边栏推荐
- Latex combat notes 2- document hierarchy and structure
- virtualBox 虚拟机网卡设置
- June training (day 09) - two point search
- Nth child selector
- 10 required AutoCAD plug-ins
- 怎么替换或禁用 WordPress 前后台默认的蓝色 favicon.ico 图标
- 618's money saving technology strategy is coming - experience the scene and get a 10 yuan cat super card!
- notepad++添加右键菜单的高级方式
- Dotnet core releases only necessary dependent files
- Deepin 编译VirtualBox实录以及编译报错解决
猜你喜欢

字节一面:网站显示不出来,怎么排查?

Byte side: how to check if the website cannot be displayed?

重构要点学习

10 required AutoCAD plug-ins

LeetCode 327. Number of interval sums

JWT思维导图

Dapr source code analysis | project overview

Interface test series -- practical application of autodiff traffic playback in integration test

Senior openstacker - Bloomberg, vexxhost upgraded to gold member of openinfra Foundation

LeetCode 6077. 巫师的总力量和
随机推荐
枚举的替代方案 —— 枚举类
June training (day 06) - sliding window
May training (day 31) - status compression
An alternative to enumeration -- Enumeration classes
Differences between single application and microservice invocation
golang reflect反射:对基本数据类型、对struct结构体进行反射(获取值)代码示例
五月集训(第26天) —— 并查集
30-year-old mind map
Interface test series -- practical application of autodiff traffic playback in integration test
JWT思维导图
June training (day 09) - two point search
五月集训(第25天) —— 树状数组
nth-child选择器
65 2D绘图(基本绘制和填充)
Wechat applet mind map
撸了一个OpenSuse作为日常工作系统
Deepin 编译VirtualBox实录以及编译报错解决
Openwrt firewall
virtualBox 虚拟机网卡设置
Moonbeam基金会与Arrington Capital共同启动1亿美金的生态增长基金以促进Moonbeam生态成长