当前位置:网站首页>[C language series] - realize the exchange of two numbers without creating the third variable
[C language series] - realize the exchange of two numbers without creating the third variable
2022-07-29 05:34:00 【Gancheng なつき】
꧁ Hello, everybody ! It is a great honor to have your visit , Let's have a long way to go in programming !꧂
* Blog column :【C All living things 】*
Introduction to this article : Realize the exchange of two numbers !
Get to know the author : Aspire to be a great programmer , Xiaobai, who is currently a sophomore in College .
Inspirational terms : The tediousness of programming , Let's study together and become interesting !
Text begins
List of articles
Add and subtract solution ideas
The opening
The previous one came from ( Tea shares ) I believe you are not very unfamiliar with the written examination questions of , Here, let's recall the practice of this problem again :
subject : Two exchanges int The value of the variable , The third variable... Cannot be used , namely a=5,b=3, After the exchange a=5,b=3;
You are right , The title is so simple and clear , Is there a trap ?— I don't think so , But if you were a classmate in the written examination at that time , I guess you can't do it ! Ha ~
Hypothetical thinking
Let's make a hypothesis here , Suppose there is no rule in the middle that it is not allowed to create the third variable ( Think like this , My rules are my rules )
I think most of my classmates are like me , It's easy , There are no conditions , Directly write an exchange function , Completed this beautiful Exchange —so easy
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
void Swap(int* x, int* y)// Implement this exchange function ( Accept with a pointer )
{
int tmp = 0;// Define an intermediate variable to exchange two values
tmp =*x;
*x = *y;
*y = tmp;
}
int main()
{
int a = 5;// The variable value given by the topic
int b = 3;
printf("exchange before a=%d b=%d\n", a, b);// Print the value before exchange
Swap(&a, &b);// Write a commutation function , take a,b Pass on your address ( Note that the value transfer cannot be changed main The value inside the function )
printf("exchange after a=%d b=%d\n", a, b);// Print the value after exchange
return 0;
}
Na , The running result you want !
OK! A small exchange function is done by us – Wait, don't you mean you can't create the third variable — Yeah
Next, let's follow - Here we try to add and subtract , Can we solve the problem
Add and subtract solution ideas
(1): First the a And b The value of the sum of the additions is assigned to a
(2): After the exchange b computing method : Is to get the original a Well , Just subtract... From the sum of the additions b Just go , At this time b It is equal to that before the exchange a 了
(3): After the exchange a computing method : use (1) Add and subtract (2) Medium b, Just before the exchange b 了
Take an example :
Is this clearer !( Stop talking nonsense , Write code quickly – forehead , good !~)
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int a = 5;
int b = 3;
printf("exchange before a=%d b=%d\n", a, b);// Print the value before exchange
a = a + b;
b = a - b;
a = a - b;
printf("exchange after a=%d b=%d\n", a, b);// Print the value after exchange
}
The result of running is the same !
Ok! The exchange was successful - Get it done ( what , You have to hand over a large number , And negative numbers , Sorry, I can't control so much code , Try to improve yourself )
All right , Uncertain , Then I'll introduce you to another method :
Exclusive or law
(1): Have learned XOR (^) This operator
In fact, every number is composed of 32 individual bite Bits are combined
XOR is the use of bite position Same as 0, Dissimilarity is 1
(2): It's no use saying more , Look at the train of thought :
First of all, will a,b The value of XOR to a On ,
Want to get the exchange b: Just use XOR a And previous b Exclusive or , Just get the previous a 了 ,( Similarly, this has to be exchanged a)
Tear your hands bite I'll show you :
Have you understood the idea , Handwritten code on :
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int a = 5;
int b = 3;
printf("exchange before a=%d b=%d\n", a, b);// Print the value before exchange
a = a ^ b;
b = a ^ b;
a = a ^ b;
printf("exchange after a=%d b=%d\n", a, b);// Print the value after exchange
return 0;
}
The running result is the same ~ Ok This is the real deal !
边栏推荐
- 浅谈范式
- 时间复杂度和空间复杂度
- Side effects and sequence points
- 微信小程序视频上传组件直接上传至阿里云OSS
- Selenium实战案例之爬取js加密数据
- ClickHouse学习(七)表查询优化
- Detailed explanation of exit interrupt
- B - identify floating point constant problems
- Occt learning 002 - environment construction
- Introduction to array learning simple question sum of two numbers
猜你喜欢
Alibaba cloud and Dingjie software released the cloud digital factory solution to realize the localized deployment of cloud MES system
Live broadcast preview | how to improve enterprise immunity through "intelligent edge security"?
Li Kou 994: rotten orange (BFS)
Selenium实战案例之爬取js加密数据
ClickHouse学习(十一)clickhouseAPI操作
B - identify floating point constant problems
Together with digital people, digital space and XR platform, Alibaba cloud and its partners jointly build a "new vision"
第三课threejs全景预览房间案例
ClickHouse学习(八)物化视图
ClickHouse学习(七)表查询优化
随机推荐
Preemptive appointment | Alibaba cloud shadowless cloud application online conference appointment opens
哈夫曼树以及哈夫曼编码在文件压缩上的应用
Using POI TL to insert multiple pictures and the same data of multiple rows of cells into the table cells of word template at one time, it is a functional component for automatic merging
【C语言系列】—文件操作详解(上)
ClickHouse学习(八)物化视图
Day 5
抢先预约 | 阿里云无影云应用线上发布会预约开启
Topological ordering of a graph of water
抽象类与接口
AR虚拟增强与现实
Day 3
167. Sum of two numbers II - enter an ordered array
With frequent data leakage and deletion events, how should enterprises build a security defense line?
Detailed explanation of serial port communication
GPIO的输入输出详解
Clickhouse learning (IV) SQL operation
Why is Google's internal tools not suitable for you?
浅谈范式
省市区三级联动(简单又完美)
存储类别