2014年7月15日 星期二

如何將兩變數的值交換卻不用到第三個變數 (轉貼)

原文一 http://stackoverflow.com/questions/5344837/how-to-swap-without-third-variable

原文二 http://stackoverflow.com/questions/1826159/swapping-two-variable-value-without-using-3rd-variable

第一種方法
 int x = 15;
 int y = 5;

 x = x + y;
 y = x - y;
 x = x - y; 

第二種方法
int A = ...;
int B = ...;
A = A ^ B;
B = A ^ B;
A = A ^ B;


沒有留言:

張貼留言