
5

不用临时变量交换两个数的值
source link: https://blog.frytea.com/archives/545/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

C 实现不用临时变量交换两个数的值(一行代码)
July 7, 2021 • Read: 31 • C/C++
本文首发于: https://blog.frytea.com/archives/545/
最近看到一个问题感觉很有意思:
“如何在不申请临时变量的情况下交换两个数的值?”
思考许久没有思路,查阅一番发现方法不少,在这里介绍四种方法:
void swap(int *p, int *q)
*a = *a ^ *b;
*b = *b ^ *a;
*a = *a ^ *b;
提示:异或运算符
^
也称XOR
运算符,它的规则是若参加运算的两个二进位同号,则结果为0
(假);异号为1
(真)。即0 ^ 0 = 0
,0 ^ 1 = 1
,1 ^ 0 = 1
,1 ^ 1 = 0
。
计算实例:
a = 3 -> 0000 0011
b = 4 -> 0000 0100
step1:
a = a ^ b
-> 0000 0011
^ 0000 0100
= 0000 0111 -> 7
step2:
b = b ^ a
-> 0000 0100
^ 0000 0111
= 0000 0011 -> 3
step3:
a = a ^ b
-> 0000 0111
^ 0000 0011
= 0000 0100 -> 4
void swap(int *p, int *q)
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
void swap(int *p, int *q)
*a = *a + *b - (*b = *a);
C/C++
中 (A = B
) 返回得到是赋值号(=
)的左面的值
计算实例:
a = 3 + 4 - (b = 3)
= 3 + 4 - 3
-> a = 4;
-> b = 3;
void swap(int *p, int *q)
*a ^= *b ^= *a ^= *b;
计算实例:
a = 3 ^ 4 = 7;
b = 4 ^ 7 = 3;
a = 7 ^ 3 = 4;
-> a = 4;
-> b = 3;
---------------------
Author: Frytea
Title: C 实现不用临时变量交换两个数的值(一行代码)
Link: https://blog.frytea.com/archives/545/
Copyright: This work by TL-Song is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK