本人愚钝,只想到了temp交换和位运算交换,其他两种方法比较巧妙,之前看到别人写过,今天突然想到了,闲来无事整理出来.
// SwapTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdio.h"
int main(int argc, char* argv[])
{
void swap1(int *a,int *b);
void swap2(int *a,int *b);
void swap3(int *a,int *b);
void swap4(int *a,int *b);
int x=3,y=5;
swap1(&x,&y);
printf("x=%d,b=%d\n",x,y);
x=3;y=5;
swap2(&x,&y);
printf("x=%d,b=%d\n",x,y);
x=3;y=5;
swap3(&x,&y);
printf("x=%d,b=%d\n",x,y);
x=3;y=5;
swap4(&x,&y);
printf("x=%d,b=%d\n",x,y);
return 0;
}
void swap1(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void swap2(int *a,int *b)
{
*a=*a^*b;
*b=*a^*b;//a.b.b
*a=*b^*a;
}
void swap3(int *a,int *b)
{
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
}
void swap4(int *a,int *b)
{
*a=*b-*a+(*b=*a);
}