關於交換數據,第一個想到的是利用中間變量。
再想想還能想到的是 加法吧,如果再想想的話可能又會有地址之類的,但是您想過沒有
相信想到加法的人有50%
能想到加法會溢出的人只有 1%吧。。。
我真的沒有想到,能看到真的是幸運的了,哈哈
view plaincopy to clipboardprint?
/************************************************************************/
/* purpose:learn how to swith number with most efficient */
/* contact:[email protected] */
/* data :2011.08.22 */
/* author:qianguozheng (錢國正) */
/************************************************************************/
#include "stdio.h"
void main()
{
int a=10;
int b=20;
printf("before switch: a=%d,b=%d\n",a,b);
/*method one : is the best one!*/
a=a^b;//a=00001010
b=a^b;//b=00010100
a=a^b;
printf("after switch: a=%d,b=%d\n",a,b);
/*
a=00001010
b=00010100
a=a^b=00011110
b=00010100
b=a^b=00001010=10
a=00011110
a=a^b=00010100=20
*/
/*method two */
/*compare to method one ,the shortback is that :
when a is the max of the type and
b is the max of the typw two
it will full overflow(溢出)
*/
a=a+b;
b=a-b;
b=a-b;
printf("after switch: a=%d,b=%d\n",a,b);
/*method three*/
int tmp;
tmp =a ;
a=b;
b=tmp;
/*this is the normal ,anyone who is called programme can do that*/
/*i will not show others to you ,just remember the first one is enough*/
}
/************************************************************************/
/* purpose:learn how to swith number with most efficient */
/* contact:[email protected] */
/* data :2011.08.22 */
/* author:qianguozheng (錢國正) */
/************************************************************************/
#include "stdio.h"
void main()
{
int a=10;
int b=20;
printf("before switch: a=%d,b=%d\n",a,b);
/*method one : is the best one!*/
a=a^b;//a=00001010
b=a^b;//b=00010100
a=a^b;
printf("after switch: a=%d,b=%d\n",a,b);
/*
a=00001010
b=00010100
a=a^b=00011110
b=00010100
b=a^b=00001010=10
a=00011110
a=a^b=00010100=20
*/
/*method two */
/*compare to method one ,the shortback is that :
when a is the max of the type and
b is the max of the typw two
it will full overflow(溢出)
*/
a=a+b;
b=a-b;
b=a-b;
printf("after switch: a=%d,b=%d\n",a,b);
/*method three*/
int tmp;
tmp =a ;
a=b;
b=tmp;
/*this is the normal ,anyone who is called programme can do that*/
/*i will not show others to you ,just remember the first one is enough*/
}
這個例子最簡單不過了,但是折射的道理卻非常的重要,我們往往在想過一個問題的解決方案之後,就高興的過頭了,忘記了對這個方案的優化,
哪怕是略微的想想,其實這些發現都很簡單,卻經常笨人所忽略。。。。。
本文出自“錢國正的專欄”