# 两个数交换

xiaoxiao2021-03-01  20

1.借助第3个变量

int a = 1,b = 2,c; c = a; / * 保存 a */ a = b; b = c;

2.不使用第3个变量 2.1 亦或方法

int a = 1,b = 2; a = a ^ b; b = a ^ b ; /* a ^ b ^ b == a */ a = a ^ b ; /* a ^ b ^ a == b */

2.2 加法方法

int a = 1,b =2; a = a + b ; /* 有越界风险 */ b = a - b ; /* a + b -b == a */ a = a - b ; /* a + b -a == b */

2.3 乘法方法

int a = 1,b = 2; a = a * b ; /* 有越界风险 */ b = a / b ; /* a * b / b == a */ a = a / b ; /* a * b / a == b */

/* 亦或方法 */ void exchange0(int *a,int *b) { *a = *a ^ *b; *b = *a ^ *b; *a = *a ^ *b; } /* 加法方法 */ void exchange1(int *a,int *b) { *a = *a + *b; *b = *a - *b; *a = *a - *b; } /* 乘法方法 */ void exchange2(int *a,int *b) { *a = *a * *b; *b = *a / *b; *a = *a / *b; }

/* 亦或方法 */ void exchange0(int *a,int *b) { if(*a == *b) return; *a = *a ^ *b; *b = *a ^ *b; *a = *a ^ *b; } /* 加法方法 */ void exchange1(int *a,int *b) { if(*a == *b) return; *a = *a + *b; *b = *a - *b; *a = *a - *b; } /* 乘法方法 */ void exchange2(int *a,int *b) { if(*a == *b) return; *a = *a * *b; *b = *a / *b; *a = *a / *b; }

“`