huangblue / Algorithm

计算机算法
0 stars 0 forks source link

用异或交换两个正整数(不需要第三个变量) #9

Open huangblue opened 7 years ago

huangblue commented 7 years ago

Using the Exclusive-OR operator, you can exchange values without the need of the temporary storage location: i1 ^= i2; i2 ^= i1; i1 ^= i2;

huangblue commented 7 years ago

//阅读版本 / Program to illustrate bitwise operators /

include

int main (void) {   unsigned int w1 = 0525u, w2 = 0707u, w3 = 0122u;   printf ("%o %o %o\n", w1 & w2, w1 | w2, w1 ^ w2);   printf ("%o %o %o\n", ~w1, ~w2, ~w3);   printf ("%o %o %o\n", w1 ^ w1, w1 & ~w2, w1 | w2 | w3);   printf ("%o %o\n", w1 | w2 & w3, w1 | w2 & ~w3);   printf ("%o %o\n", ~(~w1 & ~w2), ~(~w1 | ~w2));   w1 ^= w2;   w2 ^= w1;   w1 ^= w2;   printf ("w1 = %o, w2 = %o\n", w1, w2);   return 0; }

huangblue commented 7 years ago

//运行版本 / Program to illustrate bitwise operators /

include

int main (void) { unsigned int w1 = 0525u, w2 = 0707u, w3 = 0122u; printf ("%o %o %o\n", w1 & w2, w1 | w2, w1 ^ w2); printf ("%o %o %o\n", ~w1, ~w2, ~w3); printf ("%o %o %o\n", w1 ^ w1, w1 & ~w2, w1 | w2 | w3); printf ("%o %o\n", w1 | w2 & w3, w1 | w2 & ~w3); printf ("%o %o\n", ~(~w1 & ~w2), ~(~w1 | ~w2)); w1 ^= w2; w2 ^= w1; w1 ^= w2; printf ("w1 = %o, w2 = %o\n", w1, w2); return 0; }

huangblue commented 7 years ago

505 727 222 37777777252 37777777070 37777777655 0 20 727 527 725 727 505 w1 = 707, w2 = 525

Process returned 0 (0x0) execution time : 0.016 s Press any key to continue.

huangblue commented 7 years ago

3.4 这是个巧妙的表达式: a ˆ= b ˆ= a ˆ= b 它不需要临时变量就可以交换a 和b 的值。 这不具有可移植性。它试图在序列点之间两次修改变量a, 而这是无定义的。 例如,有人报告如下代码: int a = 123, b = 7654; a ^= b ^= a ^= b; 在SCO 优化C 编译器(icc) 下会把b 置为123, 把a 置为0。


我自己试了, codeblocks可以实现交换 gcc也可以


评价:没有什么用处,就是少用一个变量,还影响可移植性。