程式語言中的 XOR 運算子

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。

觀念請參考:
http://en.wikipedia.org/wiki/Exclusive_or
http://en.wikipedia.org/wiki/XOR_swap_algorithm



C/C++
voidswap(int&a, int&b)
{
  cout << "& Version."<< endl;
  a = a ^ b;
  b = a ^ b;
  a = a ^ b;
}

voidswap(int*a, int*b)
{
  cout << "* Version."<< endl;
  *a = *a ^ *b;
  *b = *a ^ *b;
  *a = *a ^ *b;
}

voidswap(inta, intb)
{
  cout << "Normal Version."<< endl;
  a = a ^ b;
  b = a ^ b;
  a = a ^ b;
}

問題:下列程式碼的執行結果?
intmain(void) {
  inta = 3, b = -4;
  cout << "Before swap: a = "<< a << ", b = "<< b << endl;
  swap(a, b);
  cout << "After swap: a = "<< a << ", b = "<< b << endl;
  swap(&a, &b);
  cout << "After swap: a = "<< a << ", b = "<< b << endl;
  swap(a, b);
  cout << "After swap: a = "<< a << ", b = "<< b << endl;
  return0;
}


1. 如果你理解了,那 Java C# 是否有辦法時作出相同的method
2.
其他語言呢(Perl, Python...)? 

沒有留言:

張貼留言