C语言两个数交换

来源:互联网 发布:php admin value 编辑:程序博客网 时间:2024/04/29 02:59

C语言两个数交换


    • C语言两个数交换
      • 方法
        • 1 使用临时变量
        • 2 使用异或操作
        • 3 使用加减操作
        • 4 使用入栈出栈
      • 测试
        • 1 代码
        • 2 结果

1. 方法

1.1 使用临时变量

tmp = x;x = y;y = x;

1.2 使用异或操作

注意:两个操作数不能为同一个,否则交换后为0。

x ^= y;y ^= x;x ^= y;

1.3 使用加减操作

注意:溢出并不影响数交换。

x = x + y;      y = x - y;      x = x - y;

1.4 使用入栈出栈

_asm  {      push x;       push y;       pop x;       pop y;   }  

2. 测试

2.1 代码

#include <stdio.h>#include <limits.h>#define uint unsigned int/* 宏-临时变量交换法 */#define SWAP_TMP(x,y)           \    do{                         \        typeof(x) tmp = x;      \        x = y;                  \        y = tmp;                \    }while(0)/* 宏-异或操作交换法 */#define SWAP_XOR(x,y)           \    do{                         \        x ^= y;                 \        y ^= x;                 \        x ^= y;                 \    }while(0)/* 宏-加减操作交换法 */#define SWAP_ADD(x,y)   \    do{                 \        x = x + y;      \        y = x - y;      \        x = x - y;      \    }while(0)/* 宏-出栈入栈交换法,Linux-64位gcc编译,pushpop需要操作64位数据 */#define SWAP_STACK(x,y) \    __asm__ (           \        "push %0\n\t"   \        "push %1\n\t"   \        "pop %0\n\t"    \        "pop %1"        \    :"=g" (x),"=g" (y)  \    :"0" (x),"1" (y) ) /* 方法-临时变量交换法,不用方法还可以直接交换指针,c语言不支持引用传递参数 */void swap_tmp(uint *x,uint *y){    uint tmp = *x;    *x = *y;    *y = tmp;}/* 方法-异或操作交换法 */void swap_xor(uint *x,uint *y){    *x ^= *y;    *y ^= *x;    *x ^= *y;}/* 方法-加减操作交换法 */void swap_add(uint *x,uint *y){    *x = *x + *y;    *y = *x - *y;    *x = *x - *y;}void main(){    uint x=UINT_MAX,y=11111; /* 使用最大值,测试加减法溢出是否影响交换 */    printf("add     :\t%u + %u = %u\n",x,y,x+y);    printf("before  :\tx=%2u;y=%2u\n",x,y);    /* 临时变量交换法 */    swap_tmp(&x,&y);    printf("swap_tmp:\tx=%2u;y=%2u\n",x,y);    SWAP_TMP(x,y);    printf("SWAP_TMP:\tx=%2u;y=%2u\n",x,y);     /* 异或操作交换法 */    swap_xor(&x,&y);    printf("swap_xor:\tx=%2u;y=%2u\n",x,y);    SWAP_XOR(x,y);    printf("SWAP_XOR:\tx=%2u;y=%2u\n",x,y);    /* 加减操作交换法 */    swap_add(&x,&y);    printf("swap_add:\tx=%2u;y=%2u\n",x,y);    SWAP_ADD(x,y);    printf("SWAP_ADD:\tx=%2u;y=%2u\n",x,y);    /* 出栈入栈交换法 */    long a=11111,b=22222;    printf("Before    :\ta=%2ld;b=%2ld\n",a,b);    SWAP_STACK(a,b);    printf("SWAP_STACK:\ta=%2ld;b=%2ld\n",a,b);}

2.2 结果

add     :   4294967295 + 11111 = 11110before  :   x=4294967295;y=11111swap_tmp:   x=11111;y=4294967295SWAP_TMP:   x=4294967295;y=11111swap_xor:   x=11111;y=4294967295SWAP_XOR:   x=4294967295;y=11111swap_add:   x=11111;y=4294967295SWAP_ADD:   x=4294967295;y=11111Before    : a=11111;b=22222SWAP_STACK: a=22222;b=11111
0 0
原创粉丝点击