本文主要是介绍不用第三个变量,交换两个变量的值三种方案详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Change two varible's value without the third varible
update: 2014.12.14(找到了第三种方案,简直...搞笑)
通常,交换两个变量的值的技巧就是多用一个中间变量。
source code:
#include<stdio.h>
#include<stdlib.h>int main()
{int varible_1 = 10;int varible_2 = 20;int temp = 0;//the third varibleprintf("before changing value:\nvarible_1 = %d,varible_2 = %d\n",varible_1,varible_2);temp = varible_1;varible_1 = varible_2;varible_2 = temp;printf("after changing value:\nvarible_1 = %d,varible_2 = %d\n",varible_1,varible_2);return 0;
}
jasonleaster@ubuntu:~/Desktop$ ./a.out before changing value:
varible_1 = 10,varible_2 = 20
after changing value:
varible_1 = 20,varible_2 = 10
我是听说这个问题是面试官出的,于是留意了一下。
方案一
一目了然的感觉!有木有!
最根本的思想是保留两个数据之间的“距离”,然后保持另外一个变量不变,就能交换这两个变量。
具体的操作
a = a - b;//step one 把ab之间的距离储存在a中,以丢失a的信息为代价,但是保持b不变
b = a + b;//step two 此时a是ab之间的距离。当a在b的右侧, step two时a就是大于0的数,于是b = a+b就变成原来的a了!
a = b - a;// step three.此时等式右边,利用a是原来两点之间的距离,b变成了原来的a,于是b - 原来的距离差,就是原来的b了
source code:
#include<stdio.h>
#include<stdlib.h>int main()
{int varible_1 = 10;int varible_2 = 20;printf("before changing value:\nvarible_1 = %d,varible_2 = %d\n",varible_1,varible_2);varible_1 = varible_1 - varible_2;varible_2 = varible_2 + varible_1;varible_1 = varible_2 - varible_1;printf("after changing value:\nvarible_1 = %d,varible_2 = %d\n",varible_1,varible_2);return 0;
}
jasonleaster@ubuntu:~/Desktop$ ./b.out
before changing value:
varible_1 = 10,varible_2 = 20
after changing value:
varible_1 = 20,varible_2 = 10
方案二:
位运算是个很有意思,很好玩的东西。 ---- ^
a ^ b == a异或b
0x01101001 ^ 0x 11000011 = 0x10101010
额。。。这个1010绝对是巧合。。。我随手敲出的数字,然后算的,just a demo
异或运算的几种特殊情况:
a^a = 0; //很明显咯
a^0 = a;//a 和 0做异或运算,等于本身
a^F = ~a;//这里F用来表示和a长度一致的位全1变量。a和所有位都是1的变量做异或运算,得到a的反
test :
a = 0x0101
a^a = 0x0000;
a^0x0000 = 0101;
a^0x1111 = 1010;
It‘s so obvious :-)
理解如下方法,始终要记住异或运算旨在保留两变量的“对应位相同与否”的这个信息!
重点来鸟:
a = a^b;//step one 这个语句完成后,a保存了很重要的信息,a,b对应位相同与否的信息被保存在a之中了,于此同时,b的信息未被损坏,a的信息丢失。
b = a^b;//step two 此时利用a变量个个位的信息做参照(因为a保留了ab之间的联系信息,异或),于是对a^b;做异或运算,可以得到a;同样还可以这样理解(a^b)^b = a^(b^b) = a^0 = a; 然后赋值给b,此时b变成原来初始的a
a = a^b;//step three 还是利用a保留了ab之间联系信息(异或),于是有(a^b)^(a^b)^b = a^a^b = b;
It was done!
source code:
#include<stdio.h>
#include<stdlib.h>int main()
{int varible_1 = 10;int varible_2 = 20;printf("before changing value:\nvarible_1 = %d,varible_2 = %d\n",varible_1,varible_2);varible_1 = varible_1 ^ varible_2;varible_2 = varible_1 ^ varible_2;varible_1 = varible_1 ^ varible_2;printf("after changing value:\nvarible_1 = %d,varible_2 = %d\n",varible_1,varible_2);return 0;
}
jasonleaster@ubuntu:~/Desktop$ ./c.out
before changing value:
varible_1 = 10,varible_2 = 20
after changing value:
varible_1 = 20,varible_2 = 10
方案三:
a = 1;
b = 2;
a = a*b;
b = a/b;
a = a/b;
今天才看到这方法...简直搞笑...
If there is something wrong with my explaination, please touch me by e-mail jasonleaster@gmail.com.
Thank you and wish my blog will help you.
这篇关于不用第三个变量,交换两个变量的值三种方案详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!