觀念請參考:
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...)?
2. 其他語言呢(Perl, Python...)?
沒有留言:
張貼留言