本人愚钝,只想到了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);
}
本文介绍了四种不使用临时变量进行整数交换的方法:通过临时变量交换、位运算交换、算术加减法交换及一种特殊的数学技巧交换。每种方法都提供了详细的C++代码实现。
1128

被折叠的 条评论
为什么被折叠?



