当前位置:网站首页>[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 !
边栏推荐
猜你喜欢

Occt learning 001 - Introduction

Cmu15-213 malloc lab experiment record

【C语言系列】—文件操作详解(上)

哈夫曼树以及哈夫曼编码在文件压缩上的应用

Clickhouse learning (IX) Clickhouse integrating MySQL

Container security open source detection tool - veinmind (mirror backdoor, malicious samples, sensitive information, weak password, etc.)

365 day challenge leetcode 1000 questions - day 042 array sequence number conversion + relative ranking discretization processing

无重复字符的最长字串

Clickhouse learning (VI) grammar optimization

公众号不支持markdown格式文件编写怎么办?
随机推荐
eggjs 创建应用知识点
冒泡排序 C语言
Storage category
365 day challenge leetcode1000 question - distance between bus stops on day 038 + time-based key value storage + array closest to the target value after transforming the array and + maximum value at t
ClickHouse学习(一)ClickHouse?
Camunda 1. Camunda workflow - Introduction
PyQt5:第一章第1节:使用Qt组件创建一个用户界面-介绍
About local variables
携手数字人、数字空间、XR平台,阿里云与伙伴共同建设“新视界”
终端shell常用命令
With cloud simulation platform, Shichuang technology supports the upgrading of "China smart manufacturing"
Cmu15-213 malloc lab experiment record
redis的基本使用
文件结尾
Together with digital people, digital space and XR platform, Alibaba cloud and its partners jointly build a "new vision"
Day 3
ClickHouse学习(二)ClickHouse单机安装
Cryengine3 debugging shader method
小程序中的DOM对象元素块动态排序
无重复字符的最长字串