给定两个整数a和b,交换a和b的值
设a为a0,b为b0
常规算法:
申请额外变量c,令:
c = a0;//c == a0;a == a0;b == b0;
a = b;//c == a0;a == b0;b == b0;
b= c;//c == a0;a ==b0; b == a0;
用位运算交换两个数的值,不使用任何额外空间。
首先要明确异或操作符合交换律和结合律,并且有a^a = 0;a ^0 = a;
a = a^b; // a == a0^b0; b == b0;
b = a^b ; // 注意此时a的值为a0^b0,则b == a0^b0^b0= a0;
a = a^b; // 注意此时b的值为a,a = a^b = a0^b0^a0 = b0;