务本寻道

交换x和y的值

交换指针变量x和y所指向的存储位置处存放的值,不再使用临时存储变量。直接使用位异或运算。公式:a^a=0。对任一位向量a,有a^a=0.与通常交换两个数值的 计数不一样,当移动一个值时,我们不需要第三个位置来临时存储另一个值。

(异或加密,原理相同)

  1. #include <stdio.h>
  2. #include <time.h>
  3. #include<string.h>
  4. void inplace_swap_int(int *x,int *y){//等价于inplace_normal_int函数
  5. *y=*x^*y;
  6. *x=*x^*y;
  7. *y=*x^*y;
  8. }
  9. void inplace_swap_char(char *x,char *y){//等价于inplace_normal_char函数
  10. *y=*x^*y;
  11. *x=*x^*y;
  12. *y=*x^*y;
  13. }
  14. void inplace_normal_int(int *x,int *y){
  15. int temp;
  16. temp=*x;
  17. *x=*y;
  18. *y=temp;
  19. }
  20. void inplace_normal_char(char *x,char *y){
  21. char temp;
  22. temp=*x;
  23. *x=*y;
  24. *y=temp;
  25. }
  26. /*
  27. void main(){
  28. long start,end,timeout;
  29. char a='a',b='b';
  30. char *x=&a;
  31. char *y=&b;
  32. start=clock();
  33. inplace_normal_char(x,y);
  34. end=clock();
  35. timeout=start-end;
  36. printf("x is %c,y is %c\ntimeout is %ld\n",*x,*y,timeout);
  37. }
  38. */
  39. //反序整型数组
  40. /*
  41. void reverse_array(int a[],int cnt){
  42. int first,last;
  43. for(first=0,last=cnt-1;first<last;first++,last--){
  44. inplace_swap_int(&a[first],&a[last]);
  45. }
  46. }
  47. void main(){
  48. int a[]={1,2,3,4,5};
  49. int i=0;
  50. reverse_array(a,sizeof(a)/sizeof(int));
  51. for(i=0;i<sizeof(a)/sizeof(int);i++){
  52. printf("array a is %d\n",a[i]);
  53. }
  54. }
  55. */
  56. //反序字符数组或叫字符串
  57. void reverse_char_array(char a[],int cnt){
  58. int first,last;
  59. for(first=0,last=cnt-1;first<last;first++,last--){
  60. inplace_swap_char(&a[first],&a[last]);
  61. }
  62. }
  63. void main(){
  64. char a[]="abcdefghij"; 
  65. int i=0;
  66. printf("old array a is :%s\n",a);
  67. reverse_char_array(a,strlen(a));
  68. printf("new array a is :%s\n",a);
  69. }