1 #include<stdio.h> 2 3 int main() 4 { 5 int a = 1; 6 int b = 2; 7 printf("Initial:\n"); 8 printf("a = %d\n", a); 9 printf("b = %d\n", b); 10 a = a + b; 11 b = a - b; 12 a = a - b; 13 printf("Swap:\n"); 14 printf("a = %d\n", a); 15 printf("b = %d\n", b); 16 return 0; 17 }
有人可能会觉得此算法会溢出,你可以用a = 0x7fffffff, b = 0x7ffffffe代替上面的赋值语句,来代替,得到的结果是一样的,如果还不放心,下面介绍另一种算法,通过位运算来实现变量的交换。
1 #include<stdio.h> 2 3 int main() 4 { 5 int a = 0x7fffffff; 6 int b = 0x7ffffffe; 7 printf("Initial:\n"); 8 printf("a = %d\n", a); 9 printf("b = %d\n", b); 10 a ^= b; 11 b ^= a; 12 a ^= b;; 13 printf("Swap:\n"); 14 printf("a = %d\n", a); 15 printf("b = %d\n", b); 16 return 0; 17 } 18