不使用中间变量,交换两个数值的三种方法

int main(int argc, const char * argv[]) {  

@autoreleasepool {  

int a = 10, b = 20;  

NSLog(@”before,a = %d”,a);  

NSLog(@”before,b = %d”,b);  

//第一种方法,数学运算  

/*  

a = a + b;  

b = a – b;  

a = a – b;  

*/  

//第二种方法,位异或运算  

/*  

a = a^b;  

b = a^b;  

a = a^b;  

*/  

//第三种方法,使用指针  

int *pa = &a;  

int *pb = &b;  

*pa = b;  

*pb = a;  

NSLog(@”after,a = %d”,a);  

NSLog(@”after,b = %d”,b);  

}  

return 0;

}

    原文作者:青春活力
    原文地址: https://blog.csdn.net/u011266870/article/details/53381269
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞