2013年3月14日 星期四

How to swap two variables without using a temporary variable.

Question:
How to swap two variables without using a temporary variable.


Anser:
There are 3 methods to tackle this issue.

1. XOR
a = a ^ b;
b = a ^ b;
a = a ^ b;

2. Addition and Minus
a = a + b;
b = a - b;
a = a - b;


3. Multiplying and Division
a = a * b;
b = a / b;
a = a / b;


Thinking:
It is possible overflow if you use method 2 and 3.

Why method 1 work? Because N ^ N = 0 and N ^ 0 = N, so you can think
a' = a ^ b;
b' = a' ^ b 
   = a ^ b ^ b 
   = a ^ 0 
   = a;
a'' = a' ^ b' 
    = a ^ b ^ a 
    = 0 ^ b 
    = b;



Reference:
http://emn178.pixnet.net/blog/post/92113175
http://emn178.pixnet.net/blog/post/92389195-%E9%9D%A2%E8%A9%A6%E5%B8%B8%E8%A6%8B%E7%A8%8B%E5%BC%8F%E8%80%83%E9%A1%8C-%E7%A8%8B%E5%BC%8F%E5%AF%A6%E5%81%9A


沒有留言:

張貼留言