2014-04-28 21:45
题目:就地交换两个数,不使用额外的变量。
解法:没说是整数,我姑且先当整数处理吧。就地交换可以用加法、乘法、异或完成,其中乘法和加法都存在溢出问题。三种方法都不能处理交换同一个数的情况,需要条件判断。
代码:
1 // 17.1 Do a swapping in-place. 2 #include <cstdio> 3 using namespace std; 4 5 void swap1(int &x, int &y) 6 { 7 if (x == y) { 8 return; 9 } 10 11 // what if it is double? 12 x ^= y ^= x ^= y; 13 } 14 15 void swap2(int &x, int &y) 16 { 17 if (x == y) { 18 return; 19 } 20 21 // overflow? 22 x = x + y; 23 y = x - y; 24 x = x - y; 25 } 26 27 void swap3(int &x, int &y) 28 { 29 if (x == y) { 30 return; 31 } 32 33 x = x ^ y; 34 y = x ^ y; 35 x = x ^ y; 36 } 37 38 int main() 39 { 40 int x, y; 41 42 scanf("%d%d", &x, &y); 43 printf("x = %d, y = %d\n", x, y); 44 swap1(x, y); 45 printf("x = %d, y = %d\n", x, y); 46 swap2(x, y); 47 printf("x = %d, y = %d\n", x, y); 48 swap3(x, y); 49 printf("x = %d, y = %d\n", x, y); 50 51 return 0; 52 }